15. 三数之和 双指针

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

解题思路

双指针
首先将数组排序,数组从左至右开始先固定一个数,然后在该数的右边和最后一个数各标记一个指针,如果三数之和大于0,则右指针左移;如果三数之和小于0,则左指针右移。

代码一:

class Solution(object):
    def threeSum(self, nums):
        ret = []
        if len(nums)<3:
            return ret
        nums.sort()
        i = 0
        while (i<len(nums)-2 and nums[i]<=0):
            if i>0 and nums[i]==nums[i-1]:
                i += 1 
                continue
            # 首先对原数组排序
            # 定义双指针,从i开始循环,左指针left = i + 1,右指针right = len(nums) - 1,
            # 如果这三个数相加等于0,则append,注意剔除重复的
            # 如果这三个数之和大于0,说明右指针的数太大了,需要左移,如果左移前后两个数相同,要再次左移,知道二者不一样
            # 同理,当三数之和小于0,说明左边的数太小了,需要右移,直到和上一个数不一样
            left = i + 1 
            right = len(nums) - 1 
            
            while (left<right and nums[right]>=0):
                temp = nums[i] + nums[left] + nums[right]
                if temp==0:
                    ret.append([nums[i], nums[left], nums[right]])
                    # 如果移位前后两个数相同,则需要继续移位,直到二者不一样
                    while (left<right and nums[right]==nums[right-1]):
                        right -= 1 
                    while (left<right and nums[left]==nums[left+1]):
                        left += 1
                    left += 1
                    right -= 1
                    continue 
                elif temp>0:
                    while (left<right and nums[right]==nums[right-1]):
                        right -= 1 
                    right -= 1 
                else:
                    while (left<right and nums[left]==nums[left+1]):
                        left += 1 
                    left += 1

            i += 1
        return ret

代码二:

class Solution:
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums_hash = {}
        result = list()
        # 计算每一个数有多少个
        for num in nums:
            nums_hash[num] = nums_hash.get(num, 0) + 1
        if 0 in nums_hash and nums_hash[0] >= 3:
            result.append([0, 0, 0])

        neg = list(filter(lambda x: x < 0, nums_hash))
        pos = list(filter(lambda x: x>= 0, nums_hash))
        # print(nums_hash)
        # print(neg)
        # print(pos)
        for i in neg:
            for j in pos:
                dif = 0 - i - j
                # print(dif)
                if dif in nums_hash:
                    # 如果dif是i和j中的一个,则这个数在nums中必须含有两个或以上
                    if dif in (i, j) and nums_hash[dif] >= 2:
                        result.append([i, j, dif])
                    # 为了防止重复,条件可以是在(i,j)之间或者两数之外都可以
                    if dif < i or dif > j:
                    # if dif > i and dif < j:
                        result.append([i, j, dif])
                    
        return result
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值