[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)

题意:给定值0,使三数之和等于0,返回所有情况。

思路:这题的思路和3sum closest类似。关键在于去重。代码如下:

 1 class Solution {
 2 public:
 3     vector<vector<int> > threeSum(vector<int> &num) 
 4     {
 5         vector<vector<int>> res;
 6         sort(num.begin(),num.end());
 7         if(num.size()<3)    return res;
 8 
 9         for(int i=0;i<num.size()-2;++i)
10         {
11             if(num[i]>0)   break;  //最小值大于0,返回空
12             if(i>0&&num[i]==num[i-1]) continue;   //去重
13             int l=i+1,r=num.size()-1;
14             while(l<r)
15             {
16                 int sum=num[i]+num[l]+num[r];
17                 if(sum==0)
18                 {
19                     res.push_back({num[i], num[l], num[r]});
20                     //去重
21                     while(++l<r&&num[l-1]==num[l])
22                         ;
23                     while(--r>l&&num[r]==num[r+1])
24                        ;
25                 }
26                 else if(sum<0)
27                     ++l;
28                 else
29                     r--;
30 
31             }
32         }
33         return res;    
34     }
35 };

 

posted @ 2017-07-03 00:44  王大咩的图书馆  阅读(209)  评论(0编辑  收藏  举报