题解 | #三数之和#
三数之和
https://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711
#很笨的方法调试了好久, 先处理num,把重复数据精简掉,保证重复的数最多2个,再穷举遍历
class Solution:
def threeSum(self, num: list[int]) -> list[list[int]]:# write code here
n = len(num)
res = []
if num == []:
return res
dirt = {}
snum = set(num)
for k in snum:
dirt[k] = num.count(k)
if min(num) > 0 or max(num) < 0 or n < 3:
return res
num = []
for key in dirt.keys():
val = dirt.get(key)
if key == 0 and val >=3:
res.append([0, 0, 0])
num.append(key)
elif val >= 2:
num.append(key)
num.append(key)
else:
num.append(key)
n = len(num)
s = 0
i = s+1
j = n-1
while i < j :
if num[s] + num[i]+num[j] ==0:
if sorted([num[i], num[j], num[s]]) not in res:
res.append(sorted([num[i], num[j], num[s]]))
j -= 1
if j ==i or (num[i] ==0 and num[j] ==0):
j = n-1
i += 1
if i == n-1:
s += 1
j = n - 1
i = s+ 1
return res