解题思路: 采用双重for循环来判断两个数,又加上一个while、if判断来确定后两个数
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
if len(nums) < 4:
return []
ans = []
for i in range(0, len(nums)-3):
nums_a = nums[i]
for j in range(i+1, len(nums)-2):
nums_b = nums[j]
c = j + 1
d = len(nums) - 1
while (c < d):
if nums_a + nums_b + nums[c] + nums[d] == target:
res = [nums_a, nums_b, nums[c], nums[d]]
if res not in ans:
ans.append(res)
d -= 1
elif nums_a + nums_b + nums[c] + nums[d] > target:
d -= 1
else:
c += 1
return ans
|