给定一个整型数组和一个target,求数组中两个数的和为target并返回其下标索引

Given an array of integers, return indices of the two numbers such that they add up to a specific target.You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].


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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package company.airbnb;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class AddTwoSum {
public static void main(String args[]) {
int[] arr = {2, 134, 15, 5, 7, 264, 423, 45, 3, 36};
System.out.println(twoSum3(arr, 18)[0] + "," + twoSum3(arr, 18)[1]);
}
// 最简单的方法,循环判断,通过了
public static int[] twoSum1(int[] nums, int target) {
int a = 0;
int b = 0;
for (int i = 0; i < nums.length - 1; i++)
for (int j = i + 1; j < nums.length; j++) {
if ((nums[i] + nums[j]) == target) {
a = i;
b = j;
break;
}
}
return new int[]{a, b};
}
// 采用hash表存储键值对(number[i],i),然后判断target-numbers[i]是否在hash表中
public static int[] twoSum2(int[] numbers, int target) {
int[] res = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) {
res[0] = map.get(target - numbers[i]);
res[1] = i;
return res;
} else {
map.put(numbers[i], i);
}
}
return res;
}
// 双指针实现
public static int[] twoSum3(int[] arr, int sum) {
if (arr == null) {
return null;
}
int low = 0;
int high = arr.length - 1;
int[] result = {-1, -1};
// 先排序
Arrays.sort(arr, low, high);
while (low < high) {
if (arr[low] + arr[high] == sum) {
if (arr[low] > arr[high]) {
result[0] = high;
result[1] = low;
} else {
result[0] = low;
result[1] = high;
}
break;
} else if (arr[low] + arr[high] > sum) {
high--;
} else {
low++;
}
}
return result;
}
}