LeetCode #18 4Sum
题目
解题方法
这是一道3Sum的变题,可以把它看作是遍历数组,每次在比当前数更大的数中做3Sum操作,除了多一层循环以外其他与3Sum类似,可以用头尾双指针或者哈希表来做。
再在此题的基础上引申一下,可以写出kSum的代码,将k作为一个参数传递进入函数,再进行递归调用,最终简化为在一个区间上的2Sum问题。具体实现过程超出我的水平,暂时不探讨了,可在力扣上找到答案。
代码
双指针法
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
if len(nums) < 4:
return []
res = set()
nums.sort()
for i in range(len(nums)-3):
if nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target:
break
if i 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 = j + 1
high = len(nums)-1
while low < high:
Sum = nums[i] + nums[j] + nums[low] + nums[high]
if target > Sum:
low += 1
elif target < Sum:
high -= 1
else:
res.add((nums[i], nums[j], nums[low], nums[high]))
low += 1
high -= 1
return map(list, res)

浙公网安备 33010602011771号