# leetcode: 15. 3Sum

## 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: 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]
# ]```

## AC

```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]]```

0 条评论

• ### leetcode: 33. Search in Rotated Sorted Array

leetcode: 81. Search in Rotated Sorted Array II

• ### 专访 | Recurrent AI：呼叫系统的「变废为宝」

自然语言处理是一个庞大的领域，比如普通文本与对话就是两个不同的领域，对话领域里，任务型对话又不同于闲聊型对话，问答式对话又不同于协作型对话……

• ### Python递归函数,二分查找算法

正如你们刚刚看到的，递归函数如果不受到外力的阻止会一直执行下去。但是我们之前已经说过关于函数调用的问题，每一次函数调用都会产生一个属于它自己的名称空间，如果一直...

• ### 6 从腾讯QQgame高性能服务器集群架构看“分而治之”与“自治”等分布式架构设计原则

腾讯QQGame游戏同时在线的玩家数量极其庞大，为了方便组织玩家组队游戏，腾讯设置了大量游戏室（房间），玩家可以选择进入属意的房间，并在此房间内找到可以加入的游...

• ### [剑指offer] 数值的整数次方 [剑指offer] 数值的整数次方

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。