9.4 练手 腾讯50题 3Sum

Leetcode 15. 3Sum

Given an array nums of n integers, are there elements abc in nums such that ab + 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 nums = [-1, 0, 1, 2, -1, -4],

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

想法是排序之后使用双指针,代码如下:

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        n = len(nums)
        if n < 3:
            return []
        if(n == 3):
            if(sum(nums) == 0):
                return [nums]
            else:
                return []
        nums.sort()
        if(nums[0] > 0):
            return []
        if(nums[n-1] < 0):
            return []
        result = []
        for i in range(n):
            if(i!=0 and nums[i]==nums[i-1]):
                continue
            if(nums[i] >0):
                break
            left = i+1
            right = n-1
            while(left < right):
                val = nums[i] + nums[left] + nums[right]
                if(val > 0):
                    right -= 1
                elif(val < 0):
                    left += 1
                else:
                    result = result + [[nums[i], nums[left], nums[right]]]
                    left += 1
                    right -= 1
                    while(nums[left] == nums[left-1] and left<right):
                        left = left+1
                    while (nums[right] == nums[right+1] and left<right):
                        right = right-1
        return result

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值