Problem:

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.

For example, given array S = {-1 0 1 2 -1 -4},

A solution set is:
(-1, 0, 1)
(-1, -1, 2)

Solution: 3Sum, Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Date : 2015-01-11 10:19:28
# @Author : NSSimacer
# @Version : 1.0
class Solution:
# @return a list of lists of length 3, [[val1,val2,val3]]
def threeSum(self, num):
length = len(num)
result = []
if length < 3:
return result
num.sort()
for i in xrange(length - 2):
if i > 0 and num[i] == num[i - 1]:
continue
low = i + 1
high = length - 1
target_gap = 0 - num[i]
while low < high:
if num[low] + num[high] < target_gap:
low += 1
while low < high and num[low] == num[i - 1]:
low += 1
elif num[low] + num[high] > target_gap:
high -= 1
while low < high and num[high] == num[high + 1]:
high -= 1
else:
result.append([num[i], num[low], num[high]])
low += 1
while low < high and num[low] == num[low - 1]:
low += 1
high -= 1
while low < high and num[high] == num[high + 1]:
high -= 1
return result

先排序,然后左右夹逼。时间复杂度O(n^2),空间复杂度O(1)。注意在LeetCode OJ上很容易TLE。