LeetCode--Array---4Sum

在leetcode array系列里面洗礼了2sum,3sum,这是4sum。第一个思路是按照2sum,3sum的思路,写出遍历的解法。但是跑通程序后,却提示运行时间过长,因此思考问题在哪儿。

第一反应是,算法选用的太笨重,但是做过2sum,3sum之后很难再想到更合适的算法了。

在discussion中得到了启发,算法需要通过设定条件加快速度


由此得出了最终的结果:

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        nums.sort()
        result = []
        for i in range(len(nums)-3):
            #过滤掉不可能的情况
            if nums[i] > target/4.0:
                break
            #过滤重复的数值
            if i > 0 and nums[i] == nums[i-1]:
                continue
            target2 = target-nums[i]
            for j in range(i+1,len(nums)-2):
                #对于第二个数值也考虑不可能的情况
                if nums[j] > target2/3.0:
                    break
                #对于第二个数值考虑重复的情况
                if j > i+1 and nums[j] == nums[j-1]:
                    continue
                target3 = target-target2
                k = j+1
                l = len(nums)-1
                while k
    
    
     
     k and nums[l]==nl:
                            l = l-1
                            
                    if sum
     
     
      
      target:
                        l-=1
        
        return result
     
     
    
    

这里主要添加的条件是,过滤可能的结果,以及重复数据,具体可参看代码注释。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值