leetcode|15. 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]
]

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> result;
        
        //直接调用sort()函数进行排序
        sort(nums.begin(),nums.end());

        for(int i=0;i<nums.size();i++){
            int front=i+1;
            int back=nums.size()-1;
            int target=-nums[i];
            while(front<back){
            
            int sum=nums[front]+nums[back];
            
            if(target<sum)
                --back;
            else if(target>sum)
                ++front;
            else{
                vector<int> tempRes;
                tempRes.push_back(nums[i]);
                tempRes.push_back(nums[front]);
                tempRes.push_back(nums[back]);
                result.push_back(tempRes);
                //寻找不重复的
                while(front<back&&nums[front]==tempRes[1])
                    front++;
                while(front<back&&nums[back]==tempRes[2])
                    back--;
            }
        }
            while(i+1<nums.size()&&nums[i]==nums[i+1])
                i++;
        }
        return result;
    }
};

思路是先将所有的数据进行排序,再找出符合结果的。同时也有两个指针的使用,和昨天做的蓄水桶有共同之处。
那这样的话,2 sum问题也可以先排序再查找,但是那个问题需要返回对应的位置,这种处理方法已经将原顺序打乱了,想想还是哈希表的做法最为快捷。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值