【LeetCode刷题】15 三数之和(做的很坎坷,本质是双指针)

版本1:没有充分利用排序信息,运行超时

from typing import List


def threeSum(nums: List[int]) -> List[List[int]]:
    res = []
    nums.sort()
    for r in range(len(nums)):
        if r!=len(nums)-1:
            if nums[r]==nums[r+1]:
                continue
        l = 0
        while l + 1 < r:
            if l!=0:
                if nums[l]==nums[l-1]:
                    l += 1
                    continue
            another = 0 - nums[l] - nums[r]
            if another in nums[l + 1: r]:
                res.append([nums[l], another, nums[r]])
            l += 1
    return res


if __name__ == '__main__':
    nums = [-1,0,1,2,-1,-4,-2,-3,3,0,4]
    ans = threeSum(nums)
    print(ans)

在这里插入图片描述

版本2:用了双指针的方法,但是利用函数去重

class Solution:
   def threeSum(self, nums: List[int]) -> List[List[int]]:
       n = len(nums)
       nums.sort()
       res = []
       for a in range(n - 2):
           b, c = a + 1, n - 1
           while b < c:
               temp =nums[a]+ nums[b] + nums[c]
               if temp == 0:
                   candidate=[nums[a], nums[b], nums[c]]
                   if candidate not in res:
                       res.append(candidate)
                   # res.append([nums[a], nums[b], nums[c]])
                   b += 1
                   c -= 1
               elif temp < 0:
                   b += 1
               else:
                   c -= 1
       return res

在这里插入图片描述

版本3:双指针,进循环判断是否重复

class Solution:
   def threeSum(self, nums: List[int]) -> List[List[int]]:
       n = len(nums)
       nums.sort()
       res = []
       for a in range(n - 2):
           # 对a进行去重操作
           if a != 0:
               if nums[a] == nums[a - 1]:
                   continue
           b, c = a + 1, n - 1

           while b < c:
               # 对b进行去重操作
               if b != a + 1:
                   if nums[b] == nums[b - 1]:
                       b += 1
                       continue
               # 对c进行去重操作
               if c != n - 1:
                   if nums[c] == nums[c + 1]:
                       c -= 1
                       continue
               temp =nums[a]+ nums[b] + nums[c]
               if temp == 0:
                   res.append([nums[a], nums[b], nums[c]])
                   b += 1
                   c -= 1
               elif temp < 0:
                   b += 1
               else:
                   c -= 1
       return res

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值