【LeetCode】3Sum

问题描述

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]
]

解题思路

该题最容易想到的算法就是对于数组中a,b,c全都分别遍历,找到a+b+c=0,但是该算法复杂度O(n3)太高。思考后发现3数之和等于0,必定有正有负,所以可以先对数组中数进行排序,然后i = 0, j = i + 1往后遍历,到倒数第三个数停止,排序后复杂度可以控制在O(n2)

代码

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& sum) {
        vector<vector<int>> result;
        sort(sum.begin(), sum.end());
        if (!sum.empty() && sum.back() < 0)
            return {};
        for (int k = 0; k < sum.size(); k++) {
            if (sum[k] > 0)
                break;
            if (k > 0 && sum[k] == sum[k - 1])
                continue;
            int target = 0 - sum[k];
            int i = k + 1, j = sum.size() - 1;
            while (i < j) {
                if (sum[i] + sum[j] == target) {
                    result.push_back({sum[k], sum[i], sum[j]});
                    while (i < j && sum[i] == sum[i + 1])
                        i++;
                    while (i < j && sum[j] == sum[j - 1])
                        j--;
                    i++;
                    j--;
                } 
                else if (sum[i] + sum[j] < target)
                    i++;
                else
                    j--;
            }
        }
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值