问题描述:Given an array S of n integers,are there elements a, b, c in S such that a + b + c = 0? Find all uniquetriplets in the array which gives the sum of zero.
Note:
-
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b≤ c)
-
The solution set must not contain duplicate triplets.
For example,given array S = {-1 0 1 2 -1 -4},
A solutionset is:
(-1, 0, 1)
(-1, -1, 2)
解法:主要思想为选定第一个值num[i],则转换成和为-num[i]的Two Sum问题(TwoSum的解法:
http://blog.youkuaiyun.com/woliuyunyicai/article/details/44222949)
在本题中要注意考虑消除重复结果的问题,通过跳过num[i+1]=num[i]的循环,以及在TwoSum子问题内部,消除重复现象(注意重复仅是指产生了多个相同的结果)
代码:
public class Solution{
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
// 结果数组
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
//边界处理
if(num.length < 3)
{
return list;
}
// 快速排序:或者直接使用Arrays.sort(num);
quicksort(num, 0, num.length - 1);
//Arrays.sort(num);
// 先选定一个值,注意范围为0 ~ num.length - 2
for (int i = 0; i < num.length - 2; i++) {
// 消除重复值的重复计算,注意考虑 i = 0 情况
if (i == 0 || num[i] > num[i - 1] ) {
int start = i + 1;
int end = num.length - 1;
int target = (-num[i]);// 转化为和为target的TwoSum问题
while (start < end) {
if (num[start] + num[end] > target) {
--end;
} else if (num[start] + num[end] < target) {
++start;
} else {
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(num[i]);
temp.add(num[start++]);
temp.add(num[end--]);
list.add(temp);
//注意这里的判断条件,因为前面已经有了start++,end--(开始下一轮循环)
//(这里要避免出现下面两个循环判断不成立,直接跳至下一循环的情况,若start,end不变化,则会始终循环下去)
while (start < end && num[start] == num[start - 1]) {
// 注意不可直接退出,应为可能还有其他两个数的和满足题设
++start;
}
while (start < end && num[end] == num[end + 1]) {
--end;
}
}
}
}
}
return list;
}
// 先进行一次快速排序
private void quicksort(int[] num, int start, int end) {
if (start < end) {
int mid = Partation(num, start, end);
quicksort(num, start, mid - 1);
quicksort(num, mid + 1, end);
}
}
private int Partation(int[] num, int start, int end) {
int midnum = num[end];// 选取哨兵
int index = start;
for (int i = start; i < end; i++) {
if (num[i] <= midnum) {
swap(num, index, i);
++index;
}
}
swap(num, index, end);
return index;
}
// 交换两个位置上的数值
private void swap(int[] data, int a, int b) {
int temp = data[a];
data[a] = data[b];
data[b] = temp;
}
}