File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int [] twoSum (int [] nums , int target ) {
3
+ /**
4
+ 1. understanding
5
+ - find the indices where the numbers of that index pair sum upto the target number.
6
+ - exactly one solution
7
+ - use each element only once
8
+ - return in any order
9
+ 2. strategy
10
+ - brute force:
11
+ - validate for all pair sum
12
+ - hashtable:
13
+ - assing hashtable variable to save the nums and index
14
+ - while iterate over the nums,
15
+ - calculate the diff, and check if the diff in the hashtable.
16
+ - or save new entry.
17
+ 3. complexity
18
+ - time: O(N)
19
+ - space: O(N)
20
+ */
21
+
22
+ Map <Integer , Integer > map = new HashMap <>();
23
+
24
+ for (int i = 0 ; i < nums .length ; i ++) {
25
+ int diff = target - nums [i ];
26
+ if (map .containsKey (diff )) {
27
+ return new int [] {map .get (diff ), i };
28
+ }
29
+ map .put (nums [i ], i );
30
+ }
31
+
32
+ return new int [] {};
33
+ }
34
+ }
35
+
You can’t perform that action at this time.
0 commit comments