0
点赞
收藏
分享

微信扫一扫

18. 4Sum刷题笔记

半夜放水 2022-04-29 阅读 47

是3数之和的升级版

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        n = len(nums)
        if n<4:
            return []
        nums.sort()
        if 4*nums[0]>target or 4*nums[-1]<target:
            return []
        
        output = []
        for i in range(n-3):
            if 4*nums[i]>target:
                break
            if i>0 and nums[i]==nums[i-1]:
                continue
            for j in range(i+1,n-2):
                if j>i+1 and nums[j]==nums[j-1]:
                    continue
                k = j+1
                l = n-1
                while k < l:
                    sum4 = nums[i]+nums[j]+nums[k]+nums[l]
                    if sum4 == target:
                        output.append([nums[i],nums[j],nums[k],nums[l]])
                        while k<l and nums[k]==nums[k+1]:
                            k+=1
                        while k<l and nums[l]==nums[l-1]:
                            l-=1
                        k+=1
                        l-=1
                    elif sum4<target:
                        while k<l and nums[k]==nums[k+1]:
                            k+=1
                        k+=1
                    else:
                        while k<l and nums[l]==nums[l-1]:
                            l-=1
                        l-=1

        return output
                        

运行结果:
在这里插入图片描述
注释掉后面两个剪枝判断,运行速度大大提升,这应该和数据集有关

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        n = len(nums)
        if n<4:
            return []
        nums.sort()
        if 4*nums[0]>target or 4*nums[-1]<target:
            return []
        
        output = []
        for i in range(n-3):
            if 4*nums[i]>target:
                break
            if i>0 and nums[i]==nums[i-1]:
                continue
            for j in range(i+1,n-2):
                if j>i+1 and nums[j]==nums[j-1]:
                    continue
                k = j+1
                l = n-1
                while k < l:
                    sum4 = nums[i]+nums[j]+nums[k]+nums[l]
                    if sum4 == target:
                        output.append([nums[i],nums[j],nums[k],nums[l]])
                        while k<l and nums[k]==nums[k+1]:
                            k+=1
                        while k<l and nums[l]==nums[l-1]:
                            l-=1
                        k+=1
                        l-=1
                    elif sum4<target:
                        #while k<l and nums[k]==nums[k+1]:
                            #k+=1
                        k+=1
                    else:
                        #while k<l and nums[l]==nums[l-1]:
                            #l-=1
                        l-=1

        return output
                        

在这里插入图片描述

举报

相关推荐

0 条评论