The Solution to LeetCode 15 3Sum改进版

Question:

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

上一篇的这道题的解答有点问题,结果中出现了冗余,本来想在上篇的代码的基础上做出改进,直接写出去掉冗余结果的代码,但是没 试成功,网上看了看别人对这道题的思路,有一点点启发,根据所给的例子,我的思路如下图:

Answer:

class Solution {
public:
    vector<vector<int> >*r;
    vector<vector<int>> threeSum(vector<int>& nums) {
        
        r= new vector<vector<int>>();
        sort(nums.begin(), nums.end());
        for(int i = 0; i<nums.size(); i++)
        {
            //跳过相同的i
            while(i>0 && i<nums.size ()&& nums[i] == nums[i-1])
                  i++;
                  
            int j = i + 1;
            int p = nums.size()- 1;
            
            while(j < p)
            {
                if(nums[i] + nums[j] + nums[p] == 0)
                {
                        vector<int> tmp;    
                        tmp.push_back(nums[i]);    
                        tmp.push_back(nums[j]);    
                        tmp.push_back(nums[p]);    
                        r->push_back(tmp);
                    j ++;
                    p --;
                    //跳过相同的j
                    while(j < p && nums[j] == nums[j-1])
                        j ++;
                    //跳过相同的p
                    while(p> j && nums[p] == nums[p+1])
                        p --;
                }
                else if(nums[i] + nums[j] + nums[p] < 0)
                {
                    j ++;
                    //跳过相同的j
                    while(j < p && nums[j] == nums[j-1])
                        j ++;
                }
                else
                {
                    p --;
                    //跳过相同的p
                    while(p > j && nums[p] == nums[p+1])
                        p --;
                }
            }
        }
        return *r;
    }  
}; 

Run Code Result:
Your input
[-1,0,1,2,-1,-4]
Your answer
[[-1,-1,2],[-1,0,1]]
Expected answer
[[-1,-1,2],[-1,0,1]]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值