原题目:
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.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
思路,首先
这道题的O(n3)很好想,就是一个3个for循环的遍历搜素。
通过阅读找到这篇博文
http://tech-wonderland.net/blog/summary-of-ksum-problems.html
借鉴于2 sum的方法 即在排列好的array中搜索两个数的和为sum只需要O(n)的方法
所以3sum来说的话O(logn*n)的时间几乎可以忽略不计
代码:
public class Solution {
//新的arraylist用来存放结果
List<List<Integer>> res = new ArrayList<List<Integer>>();
public List<List<Integer>> threeSum(int[] num){
int length = num.length;
if(length < 3)
return res;
quicksort(num, 0, length - 1);
for(int i = 0; i < length - 2; i++){
if(i > 0 && num[i] == num[i-1]) continue;
int pivox = num[i];
find(num, i+1, length-1, pivox);
}
return res;
}
public void find(int[]num, int start, int end, int pivotvalue){
//利用sum的方法进行时间复杂度为O(n)的计算
int scanup = start;
int scandown = end;
while(scanup < scandown){ //循环的条件
int sum = num[scanup] + num[scandown];
if(sum + pivotvalue == 0){ //分三种情况 1 三个数的和为0
List<Integer> zuhe= new ArrayList<Integer>();
zuhe.add(num[start]);
zuhe.add(num[end]);
zuhe.add(pivotvalue);
res.add(zuhe);
while(scanup < scandown && num[scanup] == num[scanup+1])
scanup++;
while(scanup < scandown && num[scandown] == num[scandown-1])
scandown--;
scandown--;
scanup++;
}
else if(sum + pivotvalue > 0){ //三个数的和大于0
scandown --;
}
else{ //三个数的和小于0
scanup++;
}
}
}
//这里需要一个quicksort的方法
//时间复杂度为O(nlogn)
public void quicksort(int[]num, int start, int end){
if(start >= end)
return;
int indexpivox = start;
int scanup = start+1;
int scandown = end;
while(scanup <= scandown){
while(scanup < end && num[scanup] <= num[indexpivox])
scanup++;
while(scandown > start && num[scandown] >= num[indexpivox])
scandown--;
if(scanup < scandown){
swap(num, scanup, scandown);
scanup++;
scandown--;
}
}
swap(num, indexpivox, scandown);
quicksort(num, start,scandown);
quicksort(num, scandown+1, end);
}
public void swap(int[]num, int scanup, int scandown){
int tem;
tem = num[scanup];
num[scanup] = num[scandown];
num[scandown] = tem;
}
}
quicksort的算法还是有bug