Skip to content

[LeetCode] 15. 三数之和 #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Animenzzzz opened this issue Sep 6, 2019 · 0 comments
Open

[LeetCode] 15. 三数之和 #75

Animenzzzz opened this issue Sep 6, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

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

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

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

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

解题思路:这题和之前做的 四数之和 类似,主要要处理好重复数字的处理,要不然会超时。先排序,然后一层循环定位第一个数,之后使用left,right两个指针来定位后两个数字。若和等于0,就加入结果;若小于0,left加1;若大于0,right减1;res使用set定义,为了自动去重。。。

C++解题:

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        if(nums.size() < 3) return {};
        set<vector<int>> res;
        sort(nums.begin(),nums.end());
        for (int i = 0; i < nums.size()-2; i++)
        {
            if(i && nums[i-1] == nums[i]) continue;//这一步去重很重要
            int left = i+1,right = nums.size() - 1;
            while (left < right)
            {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == 0)
                {
                    res.insert({nums[i],nums[left],nums[right]});
                    left++;right--;
                }else if(sum < 0) left++;
                else right--;
            }
        }
        return vector<vector<int>>(res.begin(), res.end());;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant