题目: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.
分析:http://leetcode.com/2010/04/finding-all-unique-triplets-that-sums.html
如果不用set来去除重复元素的话,需要在指针扫描的过程中进行判重。
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > res;
sort(num.begin(), num.end());
for(int i=0; i<num.size(); i++){
//cout<<"here"<<endl;
if(i>0 && num[i]==num[i-1])
continue;
int ptr1=i+1;
int ptr2=num.size()-1;
while(ptr1 < ptr2){
if(num[i]+num[ptr1]+num[ptr2] < 0)
ptr1++;
else if(num[i]+num[ptr1]+num[ptr2] > 0)
ptr2--;
else{
vector<int> v;
v.push_back(num[i]);
v.push_back(num[ptr1]);
v.push_back(num[ptr2]);
res.push_back(v);
ptr1++; ptr2--;
while(ptr1<num.size() && num[ptr1]==num[ptr1-1])
ptr1++;
while(ptr2>=0 && num[ptr2]==num[ptr2+1])
ptr2--;
}
}// end while loop
}//end for loop
return res;
}
};
再来一个Java版本的
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
Arrays.sort(num);
for(int i=0; i<num.length; i++){
int ptr1=i+1, ptr2=num.length-1;
if(i>0 && num[i]==num[i-1])
continue;
// search from two sides
while(ptr1 < ptr2){
// smaller than 0
if(num[i]+num[ptr1]+num[ptr2] < 0)
ptr1++;
// larger than 0
else if(num[i]+num[ptr1]+num[ptr2] > 0)
ptr2--;
// equal to zero
else{
ArrayList<Integer> element = new ArrayList<Integer>();
element.add(new Integer(num[i]));
element.add(new Integer(num[ptr1]));
element.add(new Integer(num[ptr2]));
// update results
result.add(element);
ptr1++; ptr2--;
while(ptr1<num.length && num[ptr1]==num[ptr1-1])
ptr1++;
while(ptr2>i && num[ptr2]==num[ptr2+1])
ptr2--;
}
}// end while loop
}// end for loop
return result;
}// end method
}// end class