Leetcode练习(Python):数组类:第16题:给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。 注意: 答案中不可以包含重复的四元组。

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

思路:和三个数的情况类似,举一反三就好。

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()
        result = []
        length = len(nums)
        limit1 = length - 3
        limit2 = length - 2
        for index1 in range(0, limit1):
            if index1 >= 1 and nums[index1] == nums[index1 - 1]:
                continue
            for index2 in range(index1 + 1, limit2):
                if index2 > index1 + 1 and nums[index2] == nums[index2 - 1]:
                    continue
                index3 = index2 + 1
                index4 = length - 1
                while index3 < index4:
                    data = nums[index1] + nums[index2] + nums[index3] + nums[index4]
                    if data < target:
                        index3 += 1
                    elif data > target:
                        index4 -= 1
                    else:
                        result.append([nums[index1],nums[index2],nums[index3],nums[index4]])
                        while index3 < index4 and nums[index3] == nums[index3 + 1]:
                            index3 += 1
                        while index3 < index4 and nums[index4] == nums[index4 - 1]:
                            index4 -= 1
                        index3 += 1
                        index4 -= 1
        return result

猜你喜欢

转载自www.cnblogs.com/zhuozige/p/12722965.html