记录一下采坑,网上的都是说O(n^2)能过,我刚开始写了个,硬是没过,后来发现卡在查找上了,
.这里的思想就是使用多的空间来减少时间,将排序后的原数组进行分类
1.正数和负数分开
2.重复和不重复的分开
3.字典记录(用于后面查找,我这里如果用list查找,无论如何都会变成O(n^3)),python自己实现一个hash表又感觉太离谱了
简单的思想,额外的空间复杂度.
理论上小于O(N^2),网上的双指针我本地测试是0.64s,这份代码是0.28s.
class Solution:
def threeSum(self, nums):
re_list = []
postive = []
postive_2 = []
negative = []
negative_2 = []
zero = []
nums.sort()
dic = dict()
for i in range(len(nums)):
if nums[i] < 0:
if nums[i] not in dic:
negative.append(nums[i])
dic[nums[i]] = 1
else:
if dic[nums[i]] == 1:
negative_2.append(nums[i])
negative_2.append(nums[i])
dic[nums[i]] = 2
elif nums[i] == 0:
zero.append(0)
else:
if nums[i] not in dic:
postive.append(nums[i])
dic[nums[i]] = 1
else:
if dic[nums[i]] == 1:
postive_2.append(nums[i])
postive_2.append(nums[i])
dic[nums[i]] = 2
if len(zero) > 2:
re_list.append([0, 0, 0])
for i in range(len(postive)):
for j in range(i + 1, len(postive)):
b = -(postive[i] + postive[j])
if b in dic:
re_list.append([postive[i],postive[j], b])
for i in range(len(negative)):
for j in range(i + 1, len(negative)):
b = (negative[i] + negative[j])*-1
if b in dic:
re_list.append([negative[i], negative[j], b])
for i in range(0, len(negative_2), 2):
b = (negative_2[i] + negative_2[i + 1])*-1
if b in dic:
re_list.append([negative_2[i],negative_2[i + 1], b])
for i in range(0, len(postive_2), 2):
b = (postive_2[i] + postive_2[i + 1])*-1
if b in dic:
re_list.append([postive_2[i],postive_2[i + 1], b])
if len(negative) > 0 and len(postive) > 0 and len(zero) > 0:
for i in range(len(postive)):
b = postive[i]*-1
if b in dic:
re_list.append([postive[i], b, 0])
return re_list