-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
44 lines (40 loc) · 1.21 KB
/
TwoSum.java
File metadata and controls
44 lines (40 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class TwoSum {
public int[] twoSumBruteForce(int[] nums, int target) {
// Time: O(n*n) Space: O(1)
for(int i = 0; i < nums.length; i++) {
for(int j = i + 1; j < nums.length; j++) {
if(nums[i] + nums[j] == target) {
return new int[] {i, j};
}
}
}
return new int[]{};
}
public int[] twoSumOptimized(int[] nums, int target) {
// Time: O(n) Space: O(n)
Map<Integer, Integer> numbersFound = new HashMap<>(nums.length);
numbersFound.put(nums[0], 0);
for(int i = 1; i < nums.length; i++) {
if(numbersFound.containsKey(target - nums[i])) {
return new int[]{ numbersFound.get(target - nums[i]), i };
}
numbersFound.put(nums[i], i);
}
return new int[]{};
}
public int[] twoSumSorted(int[] nums, int target) {
// Time: O(n) Space: O(1)
int i = 0, j = nums.length - 1;
while(i < j) {
if(nums[i] + nums[j] == target) {
// Target found
return new int[] {i, j};
} else if(nums[i] + nums[j] > target) {
j--;
} else {
i++;
}
}
return new int[]{};
}
}