题目:
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:
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 solution set is:
(-1, 0, 1)
(-1, -1, 2)
代码:
class Solution3Sum {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
// for return
ArrayList<ArrayList<Integer> > myList = new ArrayList<ArrayList<Integer> >();
// if num.length<3 return null;
if(num.length < 3) return myList;
// define three pointer: left,middle,right;
// num[left] + num[right] + num[middle] = 0, return them
int left = 0, middle = left+1, right = num.length-1;
while(left < right-1){
middle = left + 1;
int r = right;
if(num[left]>0 || num[right]<0) break;
int value = num[left] + num[r];
while(middle<r){
if(num[left]>0 || num[r]<0) break;
if( (value + num[middle]) < 0){
middle ++; // need to increase m
}else if( (value + num[middle]) == 0){
// find one pair
ArrayList<Integer> pairList = new ArrayList<Integer>();
pairList.add(num[left]);
pairList.add(num[middle]);
pairList.add(num[r]);
// remove the repeat pairs
if( myList.size()>=1 ){
// if didn't repeat, add! Think out how to optimize below code!
int length = myList.size()-1;
while( (length>= 0) && (!myList.get(length).equals(pairList)) ){
if (myList.get(length).get(0) != pairList.get(0)) {
// first numbers are different, no need to continue---they are different
myList.add(pairList);
break;
}
length--;
if((length < 0)){
myList.add(pairList);
}
} // while
}else if(myList.size()<1){
// process the first one
myList.add(pairList);
}
middle ++; // locate the middle
value = num[left] + num[--r]; // recalculate the value
}else {
// (value + num[m]) > 0), no need to probe the rest
value = num[left] + num[--r]; // recalculate the value
}
} // while(m<r)
left ++;
} //while(left < right-1)
return myList;
}
}
亮点:
1. 查找之前,先对数组排序,这样有利于处理!
2. 对已经排序的数组,简化之!
a. 考虑到非0三个元素的组合中,相同元素最多包含两次,因此,非0元素确保在简化的数组中最多只出现两次!
b. 对于0,如果原来数组中包含的个数<=3则保留之,如果超过3个,则只保留3个!
3. 对于可能出现的重复组合,在处理过程中要及时处理掉!