【LeetCode】打卡--Python3算法18. 四数之和

版权声明:转载请说明出处,谢谢 https://blog.csdn.net/Asher117/article/details/89226894

【LeetCode】打卡–Python3算法18. 四数之和

题目

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

注意:

答案中不可以包含重复的四元组。

示例:

给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。

满足要求的四元组集合为:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

结果

执行用时 : 1604 ms, 在4Sum的Python3提交中击败了32.40% 的用户
内存消耗 : 13.1 MB, 在4Sum的Python3提交中击败了76.65% 的用户

Python解答

这题目就是三数之和再加了一层循环,因此直接在三数之和代码上外加了一层循环即可

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        data = set()
        nums.sort()
        for j in range(len(nums)-3):
            if(nums[j]>=0 and nums[j]>target):
                break
            if(j>=1 and nums[j]==nums[j-1]):
                continue
            for i in range(j+1,len(nums)-2):
                m = i + 1
                n = len(nums) - 1
                while(m < n):
                    total = nums[m] + nums[n] + nums[i] + nums[j] - target
                    if(total==0):
                        data.add((nums[j],nums[i],nums[m],nums[n]))
                        m = m + 1
                        n = n - 1
                    elif(total > 0):
                        while(nums[n-1]==nums[n] and n-1 > m):
                            n = n - 1
                        n = n - 1
                    else:
                        while(nums[m+1]==nums[m] and m+1 < n):
                            m = m + 1
                        m = m + 1
        return list(data)

我们下次再见,如果还有下次的话!!!
欢迎关注微信公众号:516数据工作室
516数据工作室

猜你喜欢

转载自blog.csdn.net/Asher117/article/details/89226894