- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
Latest commit
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
importjava.util.Arrays;
importjava.util.HashMap;
importjava.util.Map;
classSolution {
publicint[] twoSum(int[] nums, inttarget) {
Map<Integer, Integer> numMap = newHashMap<>();
for (inti = 0; i < nums.length; i++) {
intcomplement = target - nums[i];
if (numMap.containsKey(complement)) {
returnnewint[]{i, numMap.get(complement)};
}
numMap.put(nums[i], i);
}
returnnewint[0];
}
}
classSolution2 {
publicint[] twoSum(int[] nums, inttarget) {
int[] sorted = Arrays.copyOf(nums, nums.length);
Arrays.sort(sorted);
inti = 0;
intj = nums.length - 1;
while (i < j) {
intsum = sorted[i] + sorted[j];
if (sum == target) {
}
elseif (sum > target) {
j--;
}
elseif (sum < target) {
i++;
}
else
break;
}
returnnewint[0];
}
}