即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

LeetCode #15 3Sum

编程语言 u012220268 9℃ 0评论
本文目录
[隐藏]

1.Description

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


2.Analysis

题目难度为:Medium


本题思路,取出a,然后将剩下的n-1个数和b+c变为2Sum问题。同理也适用于4Sum问题等


3.Code(c++)

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

转载请注明:CodingBlog » LeetCode #15 3Sum

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情