LeetCode----18. 4Sum

题目

给出一个数组和一个目标值,找出4个元素,使得它们的和为目标值。找出所有满足该条件的四元组。

Python题解

class Solution:
    def fourSum(self,nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        nums.sort()
        res = []
        for i in range(len(nums) - 3):
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            for j in range(i + 1, len(nums) - 2):
                if j > i + 1 and nums[j] == nums[j - 1]:
                    continue
                low, high = j + 1, len(nums) - 1
                while low < high:
                    sum_tmp = nums[i] + nums[j] + nums[low] + nums[high]
                    if sum_tmp == target:
                        res.append([nums[i], nums[j], nums[low], nums[high]])
                        low += 1
                        while low < len(nums) and nums[low] == nums[low - 1]:
                            low += 1
                        high -= 1
                        while high >= 0 and nums[high] == nums[high + 1]:
                            high -= 1
                    elif sum_tmp < target:
                        low += 1
                    else:
                        high -= 1
        return res

猜你喜欢

转载自blog.csdn.net/leel0330/article/details/80480414