leetcode 15. 三数之和

题目:

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

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

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

思路:

  我们首先将数组排序,接下来将我们遍历数组中的元素x,对于x,我们要找有没有接下来有序数组中的两个数之和为-x,这时我们用的方法是双指针,当nums[l]+nums[r]==-x时,进入vector中,同时r--,l++,当nums[l]+nums[r]<-x时,l++,当nums[l]+nums[r]>-x时,r--。当x>0时,我们就可以直接跳出循环,由于答案中不可以包含重复的三元组,所以我们在遍历时要记得去重

代码:

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int n = nums.size();
        vector<vector<int> > ans;
        vector<int> v(3);
        sort(nums.begin(),nums.end());
        for(int i=0;i<n;i++)
        {
            if(nums[i]>0) break;
            if(i>0&&nums[i]==nums[i-1]) continue;
            
            int k = -nums[i];
            int l = i+1;
            int r = n-1;
            while(l<r)
            {
                if(nums[l]+nums[r]==k)
                {
                    v[0] = nums[i];
                    v[1] = nums[l];
                    v[2] = nums[r];
                    ans.push_back(v);
                    while(l<r&&nums[l]==nums[l+1]) l++;
                    while(r>l&&nums[r]==nums[r-1]) r--;
                    l++;
                    r--;
                }
                else if(nums[l]+nums[r]<k) l++;
                else r--;
            }
        }
        return ans;
    }
};

 

posted @ 2018-09-02 20:12  simpleknight  阅读(158)  评论(0编辑  收藏  举报