首页 > 其他 > 详细

三数之和

时间:2021-03-28 17:52:12      阅读:22      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

   这题暴力法时间不够,需要进行优化。

  先排序是肯定的。

  1.最外层遍历所有元素都遍历一次是没问题的,但是要注意两点:1.因为排序了所以nums[i](最外循环的元素)大于0的时候就没有解了,后面都是大的直接break就好。 2.nums[i]和nums[i-1]不能相同,否则就重复了。

  2.第二第三层遍历要写成双指针的形式。j从前往后走,k从后往前走,因为每次计算ijk对应元素和target的时候,这个target大于0说明加多了,那么k往前走,小于0说明加的还不够,j往后走。这样能大幅度提升计算速度。

  3.同理,每次找到元素后,jk都要找到下一个和自己不同的元素,否则会造成重复。

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        opt = []
        if len(nums) < 3:
            return opt
        nums.sort()
        
        for i in range(len(nums)):
            if i!=0 and nums[i]==nums[i-1]:
                continue
            head = i + 1
            tail = len(nums)-1
            if nums[i] >0:
                break
            while head < tail:
                target = nums[i]+nums[head]+ nums[tail]
                if target == 0:
                    opt.append([nums[i],nums[head],nums[tail]])
                    while head<tail and nums[head]==nums[head+1]:
                        head+=1
                    while head<tail and nums[tail] == nums[tail-1]:
                        tail-=1
                    head+=1
                    tail-=1
                elif target < 0:
                    head+=1
                else:
                    tail-=1
        return opt

 

三数之和

原文:https://www.cnblogs.com/snailbuster/p/14588538.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!