LeetCode 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.

Example:
given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[ [-1, 0, 1], [-1, -1, 2] ]

解法

直接穷举所有可能的时间复杂度为O(N^3),可以考虑穷举a的所有可能,计算b+c=-a,这样就转化成了LeetCode 1,两数相加等于指定数也可以使用数组排序后从首尾开始移动计算和的方法来解决。
所以该题的算法为:
首先对nums进行升序排列,用for循环枚举第一个数字a,下标记为i,b的下标为start=i+1, end=nums.size()-1,sum = nums[i] + nums[start] + nums[end]。
若sum = 0,则得到一组解;
若sum < 0,说明需要增大值,则start++;
若sum > 0, 说明需要减小值,则end–;
这里需要注意跳过重复的值,避免产生重复的解。
该方法时间复杂度为:O(N^2)

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> result;
        if (nums.size() < 3)
            return result;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size() - 2; i++) {
            while (i > 0 && i < nums.size() && nums[i] == nums[i - 1])
                i++;
            int start = i + 1, end = nums.size() - 1;
            while (start < end) {
                int sum = nums[i] + nums[start] + nums[end];
                if (sum < 0) {
                    start++;
                    while (start < end && nums[start] == nums[start - 1])
                        start++;
                } else if (sum == 0) {
                    vector<int> tmp;
                    tmp.push_back(nums[i]);
                    tmp.push_back(nums[start]);
                    tmp.push_back(nums[end]);
                    result.push_back(tmp);
                    start++;
                    while(start < end && nums[start] == nums[start - 1])
                        start++;
                } else {
                    end--;
                    while(start < end && nums[end] == nums[end+1])
                        end--;
                }
            }
        }
        return result;
    }
}; 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值