本文共 712 字,大约阅读时间需要 2 分钟。
Q:
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
分析:参考三数之和,将四数之和转换为三数之和即可,就是多加了一层循环
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: nums.sort() res= [] if len(nums)<4: return res for j in range(len(nums)): if j>0 and nums[j]==nums[j-1]: continue # 转化为三数之和 sum1 = target - nums[j] for i in range(j+1,len(nums)): if i>j+1 and nums[i]==nums[i-1]: continue # 转化为两数之和 sum2 = sum1 - nums[i] l,r = i+1,len(nums)-1 while l
转载地址:http://gejui.baihongyu.com/