Skip to content

Commit 47f8e5a

Browse files
committed
change to o(n)
1 parent 59b8f5b commit 47f8e5a

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

two-sum/Solution.java

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,21 @@
11
public class Solution {
22
public int[] twoSum(int[] numbers, int target) {
3-
// Note: The Solution object is instantiated only once and is reused by each test case.
3+
4+
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
5+
6+
for(int i = 0; i < numbers.length; i++){
7+
m.put(target - numbers[i], i);
8+
}
9+
410
for(int i = 0; i < numbers.length; i++){
5-
for(int j = i + 1 ; j < numbers.length; j++){
6-
if (numbers[i] + numbers[j] == target) return new int[]{i + 1, j + 1};
11+
12+
Integer v = m.get(numbers[i]);
13+
14+
if(v != null && v != i){
15+
return new int[]{i + 1, v + 1};
716
}
817
}
918

10-
throw new RuntimeException();
19+
throw new RuntimeException();
1120
}
12-
}
21+
}

0 commit comments

Comments
 (0)