[Leetcode]3Sum

Given an array S of n integers, are there elements abc 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)

思路: 1.将数组排序,

          2.a 遍历 数组a[0]....a[n-1];         

          3.当 a=a[i]  时   后面的问题 就是 :  a[i+1] 到 a[n-1]中  b+c =-a  (编程之美 2.12 快速寻找满足条件的两个数  )      

                       记 b=a[j]=a[i-1]     c=a[k]=a[n-1]   

   若 b+c  < -a ,j++; 

b+c > -a  ,j--;    

b+c=-a 记录下来,并j++;

  4.还有一个问题 就是unique triplet,   所以 a=a[i] 要判断是否和a[i-1]相等,若相等,子问题已经解答。

                                                                              也要判断 b和c  是否和之前的相同,若相同,就已经判断过了。


       罗嗦这么多,直接上代码:

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> > ret;
		 ret.clear();
        sort(num.begin(),num.end());
        for(int i=0; i!=num.size();i++){
    		if(i > 0 && num[i]==num[i-1])
				continue;
			int j,k;
			j=i+1;
			k=num.size()-1;
			while(j<k){
				if(j>i+1&&num[j]==num[j-1]){ 
					j++;
					continue;
				}
				if(k<num.size()-1&& num[k]==num[k+1]){
					k--;
					continue;
				}
				 int sum = num[i] + num[j] + num[k];
				if(sum>0){
					k--;
				}else if(sum<0){
					j++;
				}else{
					vector<int> tmp;
					tmp.push_back(num[i]);
					tmp.push_back(num[j]);
					tmp.push_back(num[k]);
					ret.push_back(tmp);
					j++;
				}
			}
		}
		return ret;
            
    }
};


posted @ 2012-11-05 13:04  程序员杰诺斯  阅读(104)  评论(0编辑  收藏  举报