题目描述
给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。
注意事项
在三元组(a, b, c),要求a <= b <= c。
结果不能包含重复的三元组。
样例
如S = {-1 0 1 2 -1 -4}, 你需要返回的三元组集合的是:
(-1, 0, 1)
(-1, -1, 2)
思路
先对序列排序。因为要找三个数,每次遍历固定一个元素,然后根据三数之和调整其他两个数的位置。如果等于0,符合要求;如果大于0,小的数字右移;如果小于0,大的数字左移。遍历过程中注意跳过重复出现的数字。
代码
class Solution:
"""
@param: numbers: Give an array numbers of n integer
@return: Find all unique triplets in the array which gives the sum of zero.
"""
def threeSum(self, numbers):
# write your code here
if numbers is None or len(numbers) < 3:
return []
res = []
numbers.sort()
s = 0
e = len(numbers) - 1
while s < e:
a = numbers[s]
j = s + 1
k = e
while j < k:
b = numbers[j]
c = numbers[k]
if a + b + c == 0:
res.append([a, b, c])
if a + b + c <= 0:
while b == numbers[j] and j < k:
j += 1
if a + b + c >= 0:
while c == numbers[k] and j < k:
k -= 1
while a == numbers[s] and s < e:
s += 1
return res
复杂度分析
时间复杂度 O(n2) ,空间复杂度 O(1) 。