Skip to content

Commit 84464f9

Browse files
Create TwoSum.java
1 parent b3d6f06 commit 84464f9

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

Math/TwoSum.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class TwoSum {
2+
public int[] twoSumBrute(int[] nums, int target) { // brute-force O(n^2) time
3+
int n = nums.length;
4+
int[] result = new int[2];
5+
for(int i = 0; i<n; i++){
6+
for(int j = 0; j<n; j++){
7+
if((nums[i]+nums[j]) == target && (i!=j)){
8+
result[0] = i;
9+
result[1] = j;
10+
return result;
11+
}
12+
}
13+
}
14+
}
15+
16+
public int[] twoSumHash(int[] nums, int target) { // 1-Hash approach O(n) time
17+
Map<Integer, Integer> map = new HashMap<>();
18+
int[] result = new int[2];
19+
20+
for(int i = 0; i<nums.length; i++){
21+
int complement = target-nums[i];
22+
if(map.containsKey(complement) && map.get(complement)!= i){
23+
result[0] = i;
24+
result[1] = map.get(complement);
25+
return result;
26+
}
27+
map.put(nums[i], i);
28+
}
29+
}
30+
31+
return result;
32+
}
33+

0 commit comments

Comments
 (0)