标签:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
第一想法肯定是三层循环遍历的,时间复杂度O(n^3),但是做过了了 Two Sum ,感觉瞬间可解,随用hashtable的方法:
public List<List<Integer>> threeSum1(int[] num) {
List<List<Integer>> lists = new ArrayList<>();
HashMap<Integer, Integer> hash = new HashMap<>();
for (int i = 0; i < num.length; i++) {
hash.put(num[i], i);
}
for (int i = 0; i < num.length; i++) {
for (int j = i+1; j < num.length; j++) {
if (hash.get(0-num[i]-num[j]) != null && num[i] <= num[j] && num[j] <= 0-num[i]-num[j]) {
List<Integer> list = new ArrayList<>();
list.add(num[i]);
list.add(num[j]);
list.add(0-num[i]-num[j]);
lists.add(list);
}
}
}
return lists;
}先上代码:
public List<List<Integer>> threeSum(int[] num) {
List<List<Integer>> lists = new ArrayList<>();
Arrays.sort(num);
for (int i = 0; i < num.length - 2; i++) {
if (i == 0 || (i > 0 && num[i] != num[i-1])) {
int low = i+1, high = num.length-1, sum = 0-num[i];
while (low < high) {
if (num[low]+num[high] == sum) {
lists.add(Arrays.asList(num[i], num[low], num[high]));
while (low < high && num[low] == num[low+1]) {
low ++;
}
while (low <high && num[high] == num[high-1]) {
high --;
}
low++;
high--;
} else if (num[low] + num[high] < sum) {
low++;
} else {
high--;
}
}
}
}
return lists;
}先控制一个变量a,线性遍历。此时只需找出b,c满足b+c=-a即可。由于是排序好的,剩下的可以用二分查找的思想找出b.c。于是求解(注意要排除重复解!!!!)
标签:
原文地址:http://blog.csdn.net/my_jobs/article/details/43603901