LeetCode:18. 四数之和
1、题目描述
给定一个包含 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]
]
2、题解
2.1、解法一
class Solution: def fourSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[List[int]] """ nums.sort() print(nums) n = len(nums) i = 0 ret_list = [] while i< n-3: first,second= i,i+1 # print(first) a = nums[first] if nums[first] + nums[second] + nums[second+1] + nums[second+2] >target: i += 1 continue elif nums[first] + nums[n-3] + nums[n-2] + nums[n-1] < target: i += 1 continue else: while second< n-2: print(first,second) b = nums[second] left,right = second+1, n-1 if nums[first] + nums[second] + nums[left] + nums[left+1] > target: # second += 1 break elif nums[first] + nums[right-2] + nums[right-1] + nums[right] < target: # second += 1 break while left < right: if nums[first] + nums[second] + nums[left] + nums[right] >target: right -= 1 elif nums[first] + nums[second] + nums[left] + nums[right] < target: left += 1 else: c,d = nums[left],nums[right] ret_list.append([nums[first], nums[second], nums[left], nums[right]]) while left < right and nums[left] == c: left += 1 while left < right and nums[right] == d: right -= 1 while second < n-2 and nums[second] == b: second += 1 while i < n-3 and nums[i] == a: i += 1 return ret_list