寻找三个数的和为0

问题描述: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. 给定一个长度为n的数字串,是否存在三个元素a,b,c使得a+b+c=0,找出所有不同的元素组。不能包含重复的元素组。

样例:

Given array nums = [-1, 0, 1, 2, -1, -4],

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

思路:最粗暴的解法是 n³ 的复杂度,每层循环选中一个元素,判断和是否为0。

有一个复杂度为 n² 的算法:先将所有元素从小到大排好序,然后选取一个元素 i,另外两个元素 j,k 初始时在 i 之后的数组的两端,然后移动 j,k 的位置使得三者的和为0(其中 j 只向右移,k只向左移)。C++实现代码如下:

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

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值