- 在
HashMap
中存储numbers[i]
尚需要都少数值达到target
,以及下表i
Implementation
public class Solution {
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = new int[2];
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(numbers[i])) {
int index = map.get(numbers[i]);
result[0] = index;
result[1] = i;
break;
} else {
map.put(target - numbers[i], i);
}
}
return result;
}
}
- 设置两个指针
j
指向最大值,i
指向最小值
sum > target
: j
decrease
sum < target
: i
increase
Implementation
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int left = 0;
int right = numbers.length - 1;
int[] result = new int[2];
while (left < right) {
int sum = numbers[left] + numbers[right];
if (sum == target) {
result[0] = left + 1;
result[1] = right + 1;
break;
} else if (sum < target) {
left++;
} else {
right--;
}
}
return result;
}
}
- 设置一个
ArrayList
保存出现过的不重复的数值。
- 遍历的时候比使用
HashMap
的keySet()
更快
- 设置一个
HashMap
保存出现过得不重复的数值,以及出现次数。
find()
函数
- 当value需要两个相同的数值得到时,判断该数值出现的次数是否大于1
- 否则,判断
HashMap
是否包含这两个数值
Implementation
public class TwoSum {
private HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
private ArrayList<Integer> list = new ArrayList<Integer>();
// Add the number to an internal data structure.
public void add(int number) {
if (map.containsKey(number)) {
map.put(number, map.get(number) + 1);
}
else {
map.put(number, 1);
list.add(number);
}
}
// Find if there exists any pair of numbers which sum is equal to the value.
public boolean find(int value) {
for (int i = 0; i < list.size(); i++) {
int num1 = list.get(i);
int num2 = value - num1;
if ((num1 == num2 && map.get(num1) > 1) || (num1 != num2 && map.containsKey(num2))) {
return true;
}
}
return false;
}
}