· 4 years ago · May 28, 2021, 06:46 AM
1Input: nums = [2,7,11,15], target = 9
2Output: [0,1]
3Output: Because nums[0] + nums[1] == 9, we return [0, 1].
4
5Example 2:
6
7Input: nums = [3,2,4], target = 6
8
9 3 => 3+2 => 5 3+4 => 7
10 2 => 2+4 => 6 (1,2)
11Output: [1,2]
12Example 3:
13
14Input: nums = [3,3], target = 6
15Output: [0,1]
16
17Given a sorted array.
18
19Brute force:
20
21for (int i=0; i < nums.length-1; i++) {
22 for(int j=i+1; j < nums.length; j++){
23 }
24}
25
26int[] arr = [3,2,4]
27
28Arrays.sort(arr)
29
30// arr[]
31// 2,3,4
32
33
34int[] arr = [4,2,1,7,8] target = 8
35
36Arrays.sort(arr)
37
38// [1,2,4,7,8] O(nlogn)
39
401,8 > 8
411,7 == 8
422,8
43
44
45left = 1
46right = 8
47
48if left + right == 8
49 then return left,right;
50else if left + right < 8
51else left + right > 8
52
53
54Brute force:
55 1000,000,000 * 1000,000,000 => 4-5 years
56 1,00,00,000 => 100 ms
57
58Two pointer using sorting O(nlogn)
59
60Without sorting
61
62int[] arr = [4,2,1,7,8] target = 8
63
64HashMap<Integer,Integer> map;
65
66int[] answer = new int[2];
67
68for(int i=0; i < arr.length; i++){
69 if(map.get(target-arr[i])){
70 arr[0] = map.get(1);
71 arr[1] = map.get(2);
72 return arr;
73 }
74 map.put(arr[i],i);
75}
76HashMap in java, dictionary in python and maps in cpp
77
78[4,2,1,7] => 8
79// map.put(4,0) what we need => 4
80// map.put(2,1) what we need => 6
81// map.put(1,2) what we need => 7
82
83// map.put(7,3) what we need => 1
84
854 => 0
862 => 1
871 => 2
887 => 3
89// map.get(1)
90
91return map.get(1) map.get(7)
928 => 4
93
94
95Hash Map/ Hash table
96
97
98Main advantages:
99
1001. It is easier to find a value.
101
102Hashmap Read access : O(1)
103Array Read access : O(n)
104
105int[] discordAges = new int[320];
106
107Str[] arr = ['x' => 24, 'y' => 29,
108'z' => 20, 'a' => '32', 'mission faang' => 26,
109'newuser' => 25,'sdfsdf']
110O(n)
111
112Hash function
113
114 Hash function generation unique key
115
116Million users
117
118O(1) => operatin
119
120// get api
121map.get('y'); => hash(y) => 1301
122
123// put api
124map.put('newuser',25);
125
126Hash collision:
127
128Hash collision is caused when two different
129strings generate a same unique hash code
130
131
132[10,4,7,2,1,8,]
133
134int[] arr = new int[1000000]
135
136
137Time complexity:
138
139
140int[] product; // 1,000,000 users daily
141
142
143