[leetcode]15. 3Sum

本文介绍LeetCode上3Sum问题的一种高效解决方案。通过先排序再使用双指针技术来寻找数组中所有唯一三元组,使得这三个数相加为零。详细解释了算法流程与边界条件处理,并给出了C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://leetcode.com/problems/3sum/#/description

Given an array S of n integers, are there elements abc in S 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.

For example, given array S = [-1, 0, 1, 2, -1, -4],

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


思路:(用递归超时)

先升序排序,然后用第一重for循环确定第一个数字。

然后在第二重循环里,第二、第三个数字分别从两端往中间扫。

如果三个数的sum等于0,得到一组解。

如果三个数的sum小于0,说明需要增大,所以第二个数往右移。

如果三个数的sum大于0,说明需要减小,所以第三个数往左移。

时间复杂度:O(n2)


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值