题目
思路
遍历两个数,然后问题转化为twoSum问题。
ps:python的for循环真是不好用(⊙︿⊙)
代码
class Solution:
"""
@param numbers: Give an array
@param target: An integer
@return: Find all unique quadruplets in the array which gives the sum of zero
"""
def fourSum(self, numbers, target):
# write your code here
numbers.sort()
length = len(numbers)
res_list = []
i = 0
while i < length:
while i and i < length and numbers[i] == numbers[i - 1]:
i += 1
j = i + 1
while j < length:
while j != i + 1 and j < length and numbers[j] == numbers[j - 1]:
j += 1
if i < length and j < length:
left = j + 1; right = length - 1
print(i, j, left, right)
while left < right:
sum = numbers[left] + numbers[right] + numbers[i] + numbers[j]
if sum == target and left < right:
res_list.append([numbers[i], numbers[j], numbers[left], numbers[right]])
left += 1
while left < right and numbers[left] == numbers[left - 1]:
left += 1
elif sum > target and left < right:
right -= 1
elif left < right: left += 1
j += 1
i += 1
return res_list