题目描述:
给定一个包含 n 个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c,使得 a + b + c = 0?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
我的方法(遍历)
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
num = []
length = len(nums)
for i in range(0 , length - 2):
for j in range(i+1 , length - 1):
for k in range(j+1 , length):
if nums[i] + nums[j] + nums[k] == 0:
temp = []
temp = [nums[i] , nums[j] , nums[k]]
temp.sort()
num.append(temp)
num = list(set([tuple(t) for t in num]))
return num
问题:超出时间限制
收获:二维列表状语从句:二维数组去重
print(num)
arr = np.array(num)
print(arr)
print(set(tuple(t) for t in arr))
print(list(set(tuple(t) for t in arr)))
输出:
[[-1,0,1],[-1,-1,2],[ - 1,0,1]]
[[-1 0 1]
[-1 -1 2]
[-1 0 1]]
{(-1,-1,2),(-1,0,1)}
[(-1,-1,2),(-1,0,1)]
参考答案:
时间复杂度0(n*n),先对数组排序,遍历一遍确定一个数,然后两端逼近求另外两个数
nums = [-1, 0, 1, 2, -1, -4] arr = [] nums.sort() length = len(nums) for i in range(0 , length - 2): l = i + 1 r = length -1 if i > 0 and nums[i] == nums[i-1]: continue while l < r: sum = nums[i] + nums[l] + nums[r] if sum < 0: l = l + 1 elif sum > 0: r = r - 1 else: arr.append([nums[i],nums[l],nums[r]]) while l < r and nums[l] == nums[l + 1]: l = l + 1 while l < r and nums[r] == nums[r -1]: r = r - 1 l = l + 1 r = r - 1 print(arr)