LeetCode 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]
]
分析

给定一个数组,返回数组中和等于0的三个元素。
首先想到的是暴力解决法,三层for循环,时间复杂度是O(n^3),并且还要处理重复的问题,显然不是题目想要的解法。如果对数组先进行排序,将时间复杂度降为O(nlgn).
先对数组进行排序,然后采用左右夹逼的方法,令target = 0,使三数之和等于0,最后将三个数输出即可。

C++实现:
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());
        const int target = 0;

        auto last = nums.end();
        for (auto i = nums.begin();i < last - 2;++i){
            auto j = i + 1;
            if(i > nums.begin() && *i == *(i-1))
                continue;
            auto k = last - 1;
            while(j < k){
                if(*i + *j + *k < target){
                    ++j;
                    while(*j == *(j - 1)&&j < k)
                        ++j;
                }
                else if(*i + *j + *k > target){
                    --k;
                    while(*k == *(k+1)&&j < k)
                    --k;
                }
                else{
                    result.push_back({*i,*j,*k});
                    ++j;
                    --k;
                    while(*j == *(j - 1)&&*k == *(k + 1)&& j < k)
                    ++j;
                }
            }
        }
        return result;
    }
};
python实现
class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        nums.sort()
        for i in xrange(0, len(nums)):
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            target = 0 - nums[i]
            start, end = i + 1, len(nums) - 1
            while start < end:
                if nums[start] + nums[end] > target:
                    end -= 1  
                elif nums[start] + nums[end] < target:
                    start += 1
                else:
                    res.append((nums[i], nums[start], nums[end]))
                    end -= 1
                    start += 1
                    while start < end and nums[end] == nums[end + 1]:
                        end -= 1
                    while start < end and nums[start] == nums[start - 1]:
                        start += 1
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值