-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
46 lines (38 loc) · 1.06 KB
/
Copy pathTwoSum.java
File metadata and controls
46 lines (38 loc) · 1.06 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
45
46
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (numMap.containsKey(complement)) {
return new int[]{i, numMap.get(complement)};
}
numMap.put(nums[i], i);
}
return new int[0];
}
}
class Solution2 {
public int[] twoSum(int[] nums, int target) {
int[] sorted = Arrays.copyOf(nums, nums.length);
Arrays.sort(sorted);
int i = 0;
int j = nums.length - 1;
while (i < j) {
int sum = sorted[i] + sorted[j];
if (sum == target) {
}
else if (sum > target) {
j--;
}
else if (sum < target) {
i++;
}
else
break;
}
return new int[0];
}
}