15. 3Sum

问题描述

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.

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

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

题目链接:


思路分析

给出一个数组,找到这个数组中有三个数相加为0的所有组合。

首先固定一个元素,将问题转化为2-sum的情况,然后使用两个指针分别从排序后的数组中进行遍历,找到有相等的情况后存储,然后跳过相同的部分继续循环(因为两个数之间还可能存在另一对数使得情况满足)。两个指针遍历完毕后再将固定的数排出重复情况。

如果target小于0了,说明原来的数是一个正整数,而排序之后,这个正整数一定是一个比较小的数,是不可能由后面的数加和而来的,所以循环就可以结束了。

代码
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size(); i++){
            int target = -nums[i];
            int front = i + 1;
            int back = nums.size() - 1;
            if (target < 0)
                break;
            while (front < back){
                int sum = nums[front] + nums[back];
                if (target > sum)
                    front++;
                else if (target < sum)
                    back--;
                else{
                    vector<int> triplet(3, 0);
                    triplet[0] = nums[i];
                    triplet[1] = nums[front];
                    triplet[2] = nums[back];
                    res.push_back(triplet);

                    while (front < nums.size() && nums[front] == triplet[1]) front++;
                    while (back >= 0 && nums[back] == triplet[2]) back--;
                }
            }
            while (nums[i+1] == nums[i] && i < nums.size())
                i++;
        }
        return res;
    }
};

时间复杂度: O(n2)
空间复杂度:


反思

一开始很不理解为什么要去掉重复的部分,后来发现很关键,不论是3个数当中哪个数的重复,都会造成结果重复的情况出现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值