题目描述:
思路解析:
首先计算 nums[a] 和 nums[b] 两数之和,再利用 c、d 双指针分别进行查找,此时类似于三数之和。
四数之和与三数之和的不同之处在于:三数之和中给定了目标值为 0,而四数之和中目标值随机。
如果对 nums[a] 的判断条件仍为 nums[a] > target,则会漏掉一部分结果,举个栗子:
若数组为[- 5, - 3, - 1, - 1, 2, 3, 6],给定 target = - 6,a 对应的数值为 -5 时,nums[a] > target,但显然还应该继续向后搜索,所以这是四数之和与三数之和不同之处。
注:结果中不可以包含重复的四元组。
所以只有 a 和 b 的值可以重复,c 和 d的值不可以重复。
代码:
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
result = []
n = len(nums)
nums.sort()
for a in range(n-2): # for a in range(n):√
# if (nums[a] + nums[a+1] + nums[a+2] + nums[a+3])>target:索引超出范围
if nums[a] > 0 and target < 0: # if nums[a] > target:输出结果有问题
break
if a>0 and nums[a] == nums[a-1]:
continue
for b in range(a+1, n):
if b>a+1 and nums[b] == nums[b-1]:
continue
two_sum = nums[a] + nums[b]
if two_sum > 0 and target < 0: # if two_sum > target:报错
break
c,d = b+1, n-1
while c < d:
sum = two_sum + nums[c] + nums[d]
if sum == target:
result.append([nums[a], nums[b], nums[c], nums[d]])
c += 1
d -= 1
while c < d and nums[c] == nums[c-1]:
c += 1
while c < d and nums[d] == nums[d+1]:
d -= 1
elif sum < target:
c += 1
else:
d -= 1
return result