File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .HashMap ;
2
+ import java .util .Map ;
3
+
4
+ /*
5
+ input : array of integers, single integer target
6
+ output : indices of the two numbers that they add up to target
7
+ constraint:
8
+ 1) is integer positive?
9
+ no [-10^9, 10^9]
10
+ 2) is there any duplicates?
11
+ yes. but only one valid answer exists
12
+ 3) can i reuse elem?
13
+ no
14
+
15
+ sol1) brute force
16
+ nested for loop. tc: O(n^2), sc: O(1) when n is the length of input
17
+
18
+ sol2) better solution with hash map
19
+ iterate through the array
20
+ check if target - current elem exists
21
+ if return pair of indices
22
+ else save current elem and continue
23
+
24
+ tc : O(n), sc: O(n) when n is the length of input
25
+
26
+ */
27
+ class Solution {
28
+ public int [] twoSum (int [] nums , int target ) {
29
+ Map <Integer , Integer > prev = new HashMap <>();
30
+ for (int i = 0 ; i < nums .length ; i ++) {
31
+ int key = target - nums [i ];
32
+ if (prev .containsKey (key )) {
33
+ return new int [] {prev .get (key ), i };
34
+ }
35
+ prev .put (nums [i ], i );
36
+ }
37
+ return null ;
38
+ }
39
+ }
You can’t perform that action at this time.
0 commit comments