LeetCode 第18题. 四数之和

Posted on 2022-09-11 16:32  林安静  阅读(40)  评论(0)    收藏  举报

思路

凭借三数之和的思路终于做出来了
踩的坑主要是:
不能和三数之和一样,若$$nums[i]>target$$就马上break或者return,因为target没有明确是正数负数

收获

借助双指针(本题的left、right),先给定一个维度的值,即套一层循环,可降维解决问题,如三维将二维(三数之和),四维降三维再降二维(本题)


代码

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()
        res = []
        for i in range(len(nums) - 1):
            if i > 0 and nums[i - 1] == nums[i]:
                continue
            for j in range(i + 1, len(nums)):
                tempTarget = target - nums[i]
                if j > i + 1 and nums[j - 1] == nums[j]:
                    continue
                left = j + 1
                right = len(nums) - 1
                while left < right:
                    temp = nums[j] + nums[left] + nums[right]
                    if temp < tempTarget:
                        left += 1
                    if temp > tempTarget:
                        right -= 1
                    if temp == tempTarget:
                        res.append([nums[i], nums[j], nums[left], nums[right]])
                        while left != right and nums[left] == nums[left + 1]:
                            left += 1
                        while left != right and nums[right] == nums[right - 1]:
                            right -= 1
                        left += 1
                        right -= 1
        return res