[LeetCode]15 三数之和

题目描述

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

代码

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
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
dict = {}
for ele in nums:
if ele not in dict:
dict[ele] = 0
dict[ele] += 1

if 0 in dict and dict[0] > 2:
result = [[0,0,0]]
else:
result = []

pos = [p for p in dict if p > 0]
neg = [n for n in dict if n < 0]

for p in pos:
for n in neg:
target = -(p + n)
if target in dict:
if target == p and dict[p] > 1:
result.append([n, p, p])
elif target == n and dict[n] > 1:
result.append([n, n, p])
elif target < n or target > p or target == 0:
result.append([n, target, p])
return result