# 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: 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]
# ]
正确,但会报 Time Limit Exceeded
:
class Solution():
def threeSum(self, x):
x.sort()
res = []
for left in range(len(x) - 2):
mid, right = left + 1, len(x) - 1
while mid < right:
s = x[left] + x[mid] + x[right]
if s == 0:
if [x[left], x[mid], x[right]] not in res:
res.append([x[left], x[mid], x[right]])
mid, right = mid + 1, right - 1
elif s < 0:
mid += 1
else:
right -= 1
return res
if __name__ == '__main__':
assert Solution().threeSum([-1, 0, 1, 2, -1, -4]) == [[-1, -1, 2], [-1, 0, 1]]
assert Solution().threeSum([1 ,1, 1, -2]) == [[-2, 1, 1]]
完全正确:
class Solution():
def threeSum(self, x):
x.sort()
res = []
for left in range(len(x) - 2):
if left == 0 or x[left] != x[left-1] and x[left] <= 0:
mid, right = left + 1, len(x) - 1
while mid < right:
s = x[left] + x[mid] + x[right]
if s == 0:
res.append([x[left], x[mid], x[right]])
mid, right = mid + 1, right - 1
while mid < right and x[mid] == x[mid - 1]:
mid += 1
while mid < right and x[right] == x[right + 1]:
right -= 1
elif s < 0:
mid += 1
else:
right -= 1
return res
if __name__ == '__main__':
assert Solution().threeSum([-1, 0, 1, 2, -1, -4]) == [[-1, -1, 2], [-1, 0, 1]]
assert Solution().threeSum([1 ,1, 1, -2]) == [[-2, 1, 1]]