[Array]018 4Sum

  • 分类:Array

  • 考察知识点:Array(数组遍历) 动态规划

  • 最优解时间复杂度:O(n^3)

18. 4Sum

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.

Example:

Given array nums = [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]
]

代码:

我的解法:

class Solution:
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        nums.sort()
        res=[]
        length=len(nums)

        if length<4:
            return res
        if nums[length-1]*4target:
            return res
        
        for i in range(length-3):
            if (i!=0) and (nums[i]==nums[i-1]):
                i+=1
                continue
            for j in range(i+1,length-2):
                if (j!=i+1) and (nums[j]==nums[j-1]):
                    j+=1
                    continue
                n,m=j+1,length-1
                while(m>n):
                    sums=nums[i]+nums[j]+nums[n]+nums[m]
                    if sums>target:
                        m-=1
                    elif sumsn and nums[n+1]==nums[n]):
                            n+=1
                        while(m>n and nums[m-1]==nums[m]):
                            m-=1
                        m-=1
                        n+=1
        return res

讨论:

1.总体还是和3Sum的思路一模一样,但是我一开始的版本几乎是卡在淘汰分边缘,然而看了大神的解法,发现并没有什么区别。然后修改了一下,把很多耗时间的地方调整了一下,就更快了
2.调整的地方之一,把特别大和特别小的去了

        if nums[length-1]*4target:
            return res

3.调整的地方之二,放在了里面,改用了while循环

                        while(m>n and nums[n+1]==nums[n]):
                            n+=1
                        while(m>n and nums[m-1]==nums[m]):
                            m-=1
[Array]018 4Sum_第1张图片
foursum

你可能感兴趣的:([Array]018 4Sum)