leetcode 15. 三数之和(Three Sum)python实现

leetcode 15. 三数之和(Three Sum)python实现

1.题目描述

[15] 三数之和

https://leetcode-cn.com/problems/3sum/description/

algorithms
Medium (21.76%)
Total Accepted: 46.5K
Total Submissions: 213.6K
Testcase Example: ‘[-1,0,1,2,-1,-4]’

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0
?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
⁠ [-1, 0, 1],
⁠ [-1, -1, 2]
]

2.解答

  1. 因暴力法超时,故想办法做出优化,可先对数组进行排序,设立i, j, k三个指针,i从左向右依次移动,j和k分别指向i右边剩余的头和尾元素,根据约束条件,j和k逐步靠拢,i遍历结束即得到解。

    其中有几个优化点:i指向元素>=0或者k指向元素<=0时可停止没必要继续移动i和k;排序后遇到连续几个相等的元素,指针跳过即可。

    class Solution:
      def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        res = []
        length = len(nums)
        for i in range(length):
          if nums[i] <= 0 :
            if nums[i] > nums[i - 1] or i ==0:
              j, k = i + 1, length - 1
              while nums[k] >= 0 and j < k:
                sum = nums[i] + nums[j] + nums[k]
                if sum > 0:
                  k -= 1
                elif sum < 0:
                  j += 1
                else:
                  res.append([nums[i], nums[j], nums[k]])
                  k -= 1
                  j += 1
                  while nums[j] == nums[j - 1] and j < k:
                    j += 1
                  while nums[k] == nums[k + 1] and j < k:
                    k -= 1
          else:
            break
        return res
    
  2. 转leetcode别人的代码,先将nums中的元素做了计数存在了d这个dict中,然后对nums进行了正负元素划分,双层循环遍历,查找第三个元素是否存在于d,这里注意:遇到三个元素中有两个相等的需要验证确实存在两个。其实这里的pos和neg可以是set类型,去重后效率更高。

    class Solution:
      def threeSum(self, nums: List[int]) -> List[List[int]]:
        d = {}
        for val in nums:
            d[val] = d.get(val, 0) + 1
    
        pos = [x for x in d if x > 0]
        neg = [x for x in d if x < 0]
    
        res = []
        if d.get(0, 0) > 2:
            res.append([0, 0, 0])
    
        for x in pos:
            for y in neg:
                s = -(x + y)
                if s in d:
                    if s == x and d[x] > 1:
                        res.append([x, x, y])
                    elif s == y and d[y] > 1:
                        res.append([x, y, y])
                    elif y < s < x:
                        res.append([x, y, s])
        return res
        
    
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值