题目:三数之和
- 给定一个包含
n
个整数的数组nums
,判断nums
中是否存在三个元素 a , b , c a,b,c a,b,c ,
使得 a + b + c = 0 ? a + b + c = 0 ? a+b+c=0?找出所有满足条件且不重复的三元组。
注意:
答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路:
暴力法:做三次循环,只要每个数都不相等,且三个数之和等于0即可。
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
l = []
len_n = len(nums)
for a in range(len_n):
for b in range(len_n):
for c in range(len_n):
if (a != b) and (a != c) and (b != c) and (nums[a] + nums[b] + nums[c] == 0):
# 根据要求进行排序
l.append(sorted([nums[a],nums[b],nums[c]]))
# 取出列表中的元素,储存为元组格式,并对其求集合,删除重复项
return [list(x) for x in (set([tuple(i) for i in l]))]
这样虽然可以得出答案,但是时间复杂度为
O
(
n
3
)
O(n^3)
O(n3),显示超时
。
另外一个解法:
原文地址:https://www.cnblogs.com/snow-l/p/8981567.html
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
diction = {}
for num in nums:
if num in diction:
diction[num] += 1
else:
diction[num] = 1
dictkey = diction.keys()
pos, neg = [], []
for p in dictkey:
if p >= 0:
pos.append(p)
else:
neg.append(p)
sorted(pos)
sorted(neg)
rsts = []
rst = []
if 0 in dictkey and diction[0] > 2:
rsts.append([0, 0, 0])
pos.reverse()
for p in pos:
for n in neg:
inverse = -(p + n)
if inverse in dictkey:
if (inverse == p or inverse == n) and diction[inverse] > 1:
rst = [inverse, p, n]
rsts.append(sorted(rst))
if inverse > p or inverse < n:
rst = [inverse, p, n]
rsts.append(sorted(rst))
return rsts