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

I still remember the first I saw this problem, I immediately solve it by using two SUM. But now, this method doesn't work anymore, the test case has already changed.

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        
        left=0
        res=[]
        while left<len(nums)-2:
            target=0-nums[left]
            dic={}
            new=nums[left+1:]
            for i,item in enumerate(new):
                if target-item not in dic:
                    dic[item]=i
                else:
                    tmp=sorted([nums[left],target-item,new[i]])
                    if tmp not in res:
                        res=res+[tmp]
            left+=1

        return res

 The second solution, also need to sort the nums, then use two pointers to solve the problem. 

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res=[]
        nums.sort()
        for index in range(len(nums)-2):
            if index>0 and nums[index]==nums[index-1]:
                continue
            left=index+1
            right=len(nums)-1
            while left<right:
                tmp=[nums[index],nums[left],nums[right]]
                s=sum(tmp)
                if s==0:
                    res.append(tmp)
                    while left < right and nums[left] == nums[left + 1]:
                        left += 1
                    while left < right and nums[right] == nums[right - 1]:
                        right -= 1
                    left+=1
                    right-=1
                elif s>0:
                    right-=1
                elif s<0:
                    left+=1
        return res

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值