Skip to main content
  1. Posts/

LeetCode-18 四数之和

·1 min·

LeetCode-18 四数之和 #

Solution 1 #

枚举两个端点, 再使用双指针来确定中间的端点.

代码如下:

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()
        n = len(nums)
        ans = []
        for i in range(n - 3):
            for l in range(i + 3, n):
                j, k = i + 1, l - 1
                while j < k:
                    s = nums[i] + nums[j] + nums[k] + nums[l]
                    if s == target:
                        ans.append([nums[i], nums[j], nums[k], nums[l]])
                        j += 1
                    elif s > target:
                        k -= 1
                    else:
                        j += 1
        ans = list(set(map(tuple, ans)))
        return ans