leetcode刷题15.三数之和

1.题目

在这里插入图片描述

2.题目意思

在列表中找出三个和为0的数,返回他们。

3.代码

我的超时代码:
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        ans = []
        n = len(nums)
        for i in range(n-2):
            for j in range(i+1, n-1):
                tmp = -1*(nums[i]+nums[j])
                res = nums[j+1:]
                tmp2 = j
                while 1:
                    if tmp in res:
                        a = res.index(tmp)+tmp2+1
                        b = [nums[i],nums[j],nums[a]]
                        if b not in ans:
                            ans.append(b) 
                        if a == len(nums):
                            break
                        res = nums[a+1:]
                        tmp2 = a
                        if b == [0, 0, 0]:
                            break
                    else:
                        break
        return ans

思路:双指针

先对列表nums排序,使得结果输出都能是字典序。

从头开始依次找两个指针i,j,在剩下的列表中找值为-(nums[i]+nums[j])的数,返回,加入到结果中。

在倒数第三个例子超时了,吐了

大佬的代码:
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        res =[]
        i = 0
        for i in range(len(nums)):
            if i == 0 or nums[i]>nums[i-1]:
                l = i+1
                r = len(nums)-1
                while l < r:
                    s = nums[i] + nums[l] +nums[r]
                    if s ==0:
                        res.append([nums[i],nums[l],nums[r]])
                        l +=1
                        r -=1
                        while l < r and nums[l] == nums[l-1]:
                            l += 1
                        while r > l and nums[r] == nums[r+1]:
                            r -= 1
                    elif s>0:
                        r -=1
                    else :
                        l +=1
        return res

思路:双指针

细节很多!好评!

首先还是对列表排序,然后基本思路是:按顺序取出列表的第一个元素,然后在剩下的里面,通过双指针进行寻找。

一个很重要的细节就是:在第一个if那里,判断了nums[i]>nums[i-1],这是因为,列表sort之后,只能是升序或者相等。如果两数相等,往后搜索到的结果一定是同一个结果!所以要判断nums[i]>nums[i-1]

另一个很重要的细节就是:最里面的两个while,意义相同,也是避免搜索到相同的数值。而且一个是从前开始,一个是从后开始,这样可以极大地提高效率。

冲冲冲~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值