LeetCode--Array---4Sum

来源:互联网 发布:北京信源软件 编辑:程序博客网 时间:2024/05/01 13:09

在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 kk and nums[l]==nl:                            l = l-1                                                if sumtarget:                        l-=1                return result

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

原创粉丝点击