标签:条件 复杂度 应该 3sum self 枚举 存在 sel items
给你一个包含 n 个整数的数组?nums,判断?nums?中是否存在三个元素 a,b,c ,使得?a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
?
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
resultSet = {}
for i in range(len(nums)):
first = nums[i]
for j in range(i+1, len(nums)):
middle = nums[j]
for k in range(j+1, len(nums)):
end = nums[k]
if (first + middle + end) == 0:
tmp = [first, middle, end]
tmp.sort()
first1,middle1,end1 = tmp
if first1 in resultSet:
if middle1 in resultSet[first1]:
resultSet[first1][middle1].add(end1)
else:
resultSet[first1][middle1] = set([end1])
else:
resultSet[first1]={middle1: set([end1])}
resultList = []
for key,v in resultSet.items():
for k2,v2 in v.items():
while len(v2)>0:
resultList.append([key, k2, v2.pop()])
return resultList
毫无疑问,在这种平台上,这种无效率的做法是会超时的。
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
resultSet = []
nums.sort()
for i in range(len(nums)):
if i!=0 and (nums[i] == nums[i-1]):
continue
first = nums[i]
endInd = len(nums) - 1
for j in range(i+1, len(nums)):
if j!=i+1 and (nums[j] == nums[j-1]):
continue
middle = nums[j]
while endInd>j and (first + middle + nums[endInd]) > 0:
endInd -= 1
if endInd>j and (first + middle + nums[endInd]) == 0:
resultSet.append([first, middle, nums[endInd]])
return resultSet
标签:条件 复杂度 应该 3sum self 枚举 存在 sel items
原文地址:https://www.cnblogs.com/immortalBlog/p/13098544.html