-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
59 lines (51 loc) · 1.52 KB
/
Solution.java
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
47
48
49
50
51
52
53
54
55
56
57
方法1
import java.util.HashMap;
public class Solution {
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
int[] res = new int[2];
for (int i = 0; i < numbers.length; i++) {
if (hashMap.get(target - numbers[i]) == null) {
hashMap.put(numbers[i], i + 1);
} else {
res[0] = hashMap.get(target - numbers[i]);
res[1] = i + 1;
break;
}
}
return res;
}
public static void main(String[] args) {
int[] numbers = { 2, 7, 11, 15 };
int target = 9;
int[] res = new Solution().twoSum(numbers, target);
System.out.println(res[0] + " " + res[1]);
}
}
方法2
import java.util.HashMap;
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int l = 0, r = numbers.length - 1;
int[] res = new int[2];
while (l < r) {
int sum = numbers[l] + numbers[r];
if (sum > target)
r--;
else if (sum < target)
l++;
else {
res[0] = l + 1;
res[1] = r + 1;
break;
}
}
return res;
}
public static void main(String[] args) {
int[] numbers = { 2, 7, 11, 15 };
int target = 9;
int[] res = new Solution().twoSum(numbers, target);
System.out.println(res[0] + " " + res[1]);
}
}