15. 3Sum

来源:互联网 发布:tdi最新价格数据 编辑:程序博客网 时间:2024/05/18 00:07

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)

【思路】先整体排序,固定第一个数,第二个数从左往右,第三个数从右往左,判断他们三个的和。

class Solution {public:    vector<vector<int>> threeSum(vector<int>& nums) {        vector<vector<int>> result;        vector<int> temp;        int len = nums.size();        if(len<3) return result;        sort(nums.begin(), nums.end());        for(int i = 0; i < len; i++)        {            while((i>0)&& i < len && (nums[i]==nums[i-1]))            i++;           int j = i+1;           int k = len-1;           while(j < k)           {               int sum = nums[i]+nums[j]+nums[k];               if(sum==0)               {                   temp.push_back(nums[i]);                   temp.push_back(nums[j]);                   temp.push_back(nums[k]);                   result.push_back(temp);                   temp.clear();                   j++;                   k--;                              while(j < k && nums[j]==nums[j-1])                j++;                while(j < k&& nums[k]==nums[k+1])                k--;               }                else if(sum < 0)                {                    j ++;                    //skip same j                    while(j < k && nums[j] == nums[j-1])                        j ++;                }                else                {                    k --;                    //skip same k                    while(k > j && nums[k] == nums[k+1])                        k --;           }        }        }        return result;    }};


0 0
原创粉丝点击