美文网首页
LeetCode 3Sum

LeetCode 3Sum

作者: codingcyx | 来源:发表于2018-04-20 11:34 被阅读0次

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

Solution:

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        int n = nums.size();
        sort(nums.begin(), nums.end());
        for(int i = 0; i<n-2; i++){
            if(i > 0 && nums[i] == nums[i-1])
                continue;
            int target = 0 - nums[i], left = i+1, right = n-1;
            while(left < right){
                if(nums[left] + nums[right] == target){
                    res.push_back({nums[i], nums[left], nums[right]});
                    while(left < right && nums[left+1] == nums[left]) left++;
                    while(left < right && nums[right] == nums[right-1]) right--;
                    left++; right--;
                }
                else if(nums[left] + nums[right] < target)
                    left++;
                else right--;
            }
        }
        return res;
    }
};

注意语法

res.push_back({nums[i], nums[left], nums[right]});

相关文章

网友评论

      本文标题:LeetCode 3Sum

      本文链接:https://www.haomeiwen.com/subject/fsyakftx.html