leetcode 15 3Sum

Given an array nums of n integers, are there elements abc in nums such that a + bc = 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]
]

给定一个数组,求其3个元素和为0的所有集合。由于是二刷,第一想法居然是回溯法,递归找出所有3个元素的集合,然后选择符合条件的集合。回溯法用来解决复杂的,规模较大的问题很好使用,可以说是很多问题的通解。但是本题应该不需要这个略显笨重的算法,三数之和的问题可以由两数之和的问题推广而来,我们将数组排好序后,从左到右遍历数组,假设遍历到第i个元素,然后设置双指针,分别从第i+1和数组尾端进行夹逼。若三数之和大于0,右侧指针向左移;若三数之和小于0,左侧指针向右移。在这个过程中,我们需过滤掉重复的情况,共有三个位置,第一层遍历第i个元素、遍历左指针和右指针的时候。排序的算法复杂度为O(nlogn),找出符合的集合复杂度为O(n^2),故算法总的复杂度为O(n^2)。代码记录如下:

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ret;
        sort(nums.begin(), nums.end());
        int length = nums.size();
        for(int i = 0; i < length; i++)
        {
            if(i > 0 && nums[i] == nums[i - 1])
                continue;
            int target = -nums[i];
            int j = i + 1;
            int k = length - 1;
            while(j < k)
            {
                if(nums[j] + nums[k] == target)
                {
                    ret.push_back({nums[i], nums[j], nums[k]});
                    j++;
                    k--;
                    while(j < k && nums[j] == nums[j - 1])  //nums[j] == nums[j - 1] not nums[j] == nums[j + 1]
                        j++;
                    while(j < k && nums[k] == nums[k + 1])
                        k--;
                }
                else if(nums[j] + nums[k] > target)
                {
                    k--;
                }
                else
                {
                    j++;
                }
            }
        }
        return ret;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值