[LeetCode] 15. 3Sum

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]
]

思路

  • 简化思路
    • 将三数相加求零的问题简化为target待定的两数和问题。
    • 将数组排序,方便排重。
    • 左右指针,在确定基础数字后,依序将最大数和最小数相加,减少无用的算术。
  • 复杂性分析:
    • 时间复杂度:O(n^2).
    • 空间复杂度:O(n).(待确定)

题解

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int> > ret;
        int len = nums.size();
        if (len<3)
            return ret;
        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]);
                    ret.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 ret;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值