Leetcode刷题笔记49-三数之和

1. 题目

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

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

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

2. 解答

C++

先排序,然后左右夹逼,复杂度 O(n )。
这个方法可以推广到 k-sum ,先排序,然后做 k-2 次循环,在最内层循环左右夹逼,时间复杂度是O(max{nlogn,n })。

// 3Sum
// 先排序,然后左右夹逼,注意跳过重复的数
// Time Complexity: O(n^2),Space Complexity: O(1)
class Solution {
    public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> result;
        if (nums.size() < 3) return result;
        sort(nums.begin(), nums.end());
        const int target = 0;
        auto last = nums.end();
        for (auto i = nums.begin(); i < last-2; ++i) {
            if (i > nums.begin() && *i == *(i-1)) continue;
            auto j = i+1;
            auto k = last-1;
            while (j < k) {
                if (*i + *j + *k < target) {
                    ++j;
                    while(*j == *(j - 1) && j < k) ++j;
                } else if (*i + *j + *k > target) {
                    --k;
                    while(*k == *(k + 1) && j < k) --k;
                } else {
                    result.push_back({ *i, *j, *k });
                    ++j;
                    --k;
                    while(*j == *(j - 1) && j < k) ++j;
                    while(*k == *(k + 1) && j < k) --k;
                }
            }
        }
        return result;
    }
};

猜你喜欢

转载自www.cnblogs.com/Joyce-song94/p/9227830.html
今日推荐