Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class Solution
  5. {
  6. public static int[] GetIndicesOfItemWeights(int[] arr, int limit)
  7. {
  8. // your code goes here
  9. if(arr == null || arr.Length == 0)
  10. {
  11. return new int[0]; // empty array
  12. }
  13.  
  14. // assume that the array is not empty
  15. var set = new HashSet<int>(); // O(n)
  16.  
  17. var length = arr.Length;
  18. for(int index = 0; index < length; index++)
  19. {
  20. var visit = arr[index]; // 4, 6, 10, 15
  21. var search = limit - visit; // 17, 15, 11, 6
  22. if(set.Contains(search)) // true
  23. {
  24. return new int[]{index, Array.LastIndexOf(arr, search)}; // 15, 6 [3, 1]
  25. }
  26.  
  27. set.Add(visit); // 4, 6 , 10,
  28. }
  29.  
  30. return new int[0];
  31. }
  32.  
  33. static void Main(string[] args)
  34. {
  35. var result = GetIndicesOfItemWeights(new int[]{4, 6, 10,15,16}, 21);
  36. foreach(var item in result)
  37. {
  38. Console.WriteLine(item);
  39. }
  40. }
  41. }
  42.  
  43. // 3 - 15, 1 - 6, 15 + 6 = 21
  44. // two items ->
  45. // sorted array -> O(nlogn)
  46. // n(n-1) -> O(n^2)
  47. // brute force
  48. // for(int first = 0; first < length - 1; first ++)
  49. // for(int second = first + 1; second < length; second++)
  50. // sum = arr[first] + arr[second]
  51. // return new int[]{first, second}
  52. // Array.Sort(arr) -> ascending order
  53. // two pointers 4, 16 -> 20 < 21, -> 6 + 16 = 22, 6 + 15
  54. // O(n)
  55. // data search ->
  56. // extra ->
  57. // 4, 17 in hashset -> Dictionary<int, int>, value, index
  58. // <4, 0>,
  59. // 6 -> 15 , add <6, 1> to the table
  60. // when we find 4, 21-4 = 17.
  61. // Array.IndexOf(value) -> first occurrence -> hashtable -> hashset -> data search
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement