TwoSum
LeetCode 上的第一道TwoSum 是这样的
Given an array of integers, find two numbers such that they add up to a specific target number。
(在一个给定的数组中找两个数相加等于某个特定值,返回这两个数在数组中的下标)
第一种解法粗暴简单。直接暴力法遍历两次数组,时间复杂度O(n²)。
第二种解法是把数存入到Hash table中(key为数值,value为下标),时间复杂度O(n) 。
public int[] twoSum(int[] numbers, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < numbers.length; i++) {
int x = numbers[i];
if (map.containsKey(target - x)) {
return new int[] { map.get(target - x) + 1, i + 1 }; }
map.put(x, i); }
throw new IllegalArgumentException("No two sum solution");
}
TwoSum II-176
TwoSum II改变的条件则是所给的数组是有序的。
所以我们可以用二分查找法:
// 二分查找
public int[] twoSum(int[] numbers, int target) {
// Assume input is already sorted.
for (int i = 0; i < numbers.length; i++) {
int j = bsearch(numbers, target - numbers[i], i + 1);
if (j != -1) {
return new int[] { i + 1, j + 1 };
}
}
throw new IllegalArgumentException("no tow sum solution");
}
private int bsearch(int[] a, int key, int start) {
int l = start, r = a.length - 1;
while (l < r) {
int m = (l + r) / 2;
if (a[m] < key)
l = m + 1;
else
r = m;
}
return (l == r && a[l] == key) ? l : 0;
}
或者设置两个指针,一个从头开始遍历,一个从尾开始遍历。
// 两个指针
public int[] twoSum(int[] numbers, int target) {
int a[] = new int[2];
int i = 0, j = numbers.length - 1;
while (i < j) {
int x = numbers[i] + numbers[j];
if (x < target)
i++;
else if (x > target)
j--;
}
a[0] = i;
a[1] = j;
return a;
}
TwoSum III-170
Design and implement a TwoSum class. It should support the following operations:add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
这道题让我们设计一个Two Sum的数据结构,跟LeetCode的第一道题Two Sum没有什么太大的不一样.
用哈希表的解法,我们把每个数字和其出现的次数建立映射,然后我们遍历哈希表,对于每个值,我们先求出此值和目标值之间的差值t,然后我们需要分两种情况来看,当差值t等于当前值时,如果此时哈希表的映射次数大于1,则表示哈希表中还有另一个和当前值相等的数字,二者相加就是目标值。当前值不等于差值t,那么只要哈希表中有差值t就返回True。
private Map<Integer,Integer> table=new HashMap<>();
public void add(int input){
int count=table.containsKey(input)?table.get(input):0;
table.put(input, count+1);
}
public boolean find(int val){
for (Map.Entry<Integer, Integer> entry:table.entrySet()) {
int num=entry.getKey();
int t=val-num;
if(t==num){
if(entry.getValue()>=2) return true;
}else if(table.containsKey(t))
return true;
}
return false;
}