解法1:普通解法
/**
* @param numbers int整型一维数组
* @param target int整型
* @return int整型一维数组
*/
public int[] twoSum(int[] numbers, int target) {
int[] res = new int[2];
int pre, last;
for (int i = 0; i < numbers.length; i++) {
pre = numbers[i];
last = target - pre;
for (int j = i+1; j < numbers.length; j++) {
if (last == numbers[j]) {
res[0] = i+1;
res[1] = j+1;
}
}
}
return res;
}
解法2:高级解法
思路,尽量减少遍历。什么可以减少遍历?hash表。所以hashMap
hashMap也得遍历两次,一次把所有的值全扔进去,第二次才能开始找,那么有没有办法一次搞定?有,如下
public int[] twoSum2(int[] numbers, int target) {
Map<Integer, Integer> map = new HashMap<>();
int n = numbers.length;
for (int i = 0; i < n; i++) {
int cur = numbers[i];
int diff = target - cur;
if (map.containsKey(diff)) {
return new int[]{map.get(cur) + 1, i + 1};
}
map.put(cur, i);
}
throw new RuntimeException("result is not exist");
}
这样写,可以,但是不够信达雅。改良一下,如下:
public int[] twoSum2(int[] numbers, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0, tmp; i < numbers.length; i++) {
tmp = target - numbers[i];
if (map.containsKey(tmp)) {
return new int[]{map.get(tmp) + 1, i + 1};
}
map.put(numbers[i], i);
}
throw new RuntimeException("result is not exist");
}