Fork me on GitHub

Leetcode15.3Sum三数之和

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ]

 

 

双指针加去重

 

class Solution {
public:
    vector<vector<int> > threeSum(vector<int>& nums) {
        int len = nums.size();
        sort(nums.begin(), nums.end());
        map<int, pair<int, int> > check;
        vector<vector<int> > res;
        for(int i = 0; i < len - 2; i++)
        {
            int low = i + 1;
            int high = len - 1;
            while(low < high)
            {
                if(nums[low] + nums[high] == -nums[i])
                {
                    res.push_back({nums[i], nums[low], nums[high]});
                    //去重
                    while(nums[low] == nums[low + 1])
                        low++;
                    low++;
                }
                if(nums[low] + nums[high] > -nums[i])
                {
                    high--;
                }
                else
                {
                    low++;
                }
            }
            //去重
            while(nums[i] == nums[i + 1])
                i++;
        }
        return res;
    }
};

 

posted @ 2018-11-17 18:51  lMonster81  阅读(118)  评论(0编辑  收藏  举报
/*评论*/ /*top按钮*/

/* 网易云控件 */