18. 4Sum (python)

来源:互联网 发布:刷帮豆软件 编辑:程序博客网 时间:2024/06/04 19:12

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target?
Find all unique quadruplets in the array which gives the sum of target.
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
题意:在数组S中找到四个元素相加和为0,当然要去重
思路:采用快速排序法只排一次,每次取一个数x,问题转化为target-x的3sum问题
时间复杂度为O(n^3)
第一个:每次取一个数,只将该元素后续的列表中查找target-x的3sum和;
第二个:每次取一个数,需要判断是否和前一个数重复(循环起始数除外),只有不重复才进行3sum计算,重复则continue
3sum计算同理,就能避免重复
第三个:在进行2sum计算,若2sum的和等于target后,需要将左右指针移位,过滤后续重复元素,直到元素不重复再计算2sum之和
Runtime: 892 ms

class Solution(object):    def fourSum(self, nums, target):        if len(nums)<=3:            return  []        nums=sorted(nums)        four=[]        for i in range(0,len(nums)-3):            if nums[i]==nums[i-1] and i!=0:                continue            for j in range(i+1,len(nums)-2):                if nums[j]==nums[j-1] and j!=i+1:                    continue                t=target-nums[i]-nums[j]                l,r=j+1,len(nums)-1                while l<r:                    s=nums[r]+nums[l]                    if s==t:                        four.append([nums[i],nums[j],nums[l],nums[r]])                        l+=1                        r-=1                        while l<r and nums[l]==nums[l-1]:                            l+=1                        while l<r and nums[r]==nums[r+1]:                            r-=1                    elif s<t:                        l+=1                    else:                        r-=1        return four
0 0
原创粉丝点击