[英]3Sum Problem in Python 3, Time Limit Exceeded in Leetcode
我尝试在 python 3 中解决 Leetcode 上的 3Sum 问题,但它表明我的解决方案已超过时间限制。 3Sum问题如下:给定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: List[int]) -> List[List[int]]
res =[]
size = len(nums)
nums.sort()
for i in range(size-2):
if i> 0 and nums[i] == nums[i-1]:
continue
low = i+1
high = size - 1
while(low<high):
val = nums[low]+nums[high] + nums[i]
if(val < 0) or ((low < high) and nums[low] == nums[low+1]):
low = low + 1
elif( val > 0) or ((low < high) and nums[high] == nums[high-1]):
high = high - 1
else:
res.append( (nums[i], nums[low], nums[high]))
return(res)
有人可以告诉我是什么错误。
你必须这样做 O(N ^ 2)。 O(N ^ 3) 是不可接受的:
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
unique_triplets = []
nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
lo = i + 1
hi = len(nums) - 1
while lo < hi:
target_sum = nums[i] + nums[lo] + nums[hi]
if target_sum < 0:
lo += 1
if target_sum > 0:
hi -= 1
if target_sum == 0:
unique_triplets.append((nums[i], nums[lo], nums[hi]))
while lo < hi and nums[lo] == nums[lo + 1]:
lo += 1
while lo < hi and nums[hi] == nums[hi - 1]:
hi -= 1
lo += 1
hi -= 1
return unique_triplets
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
found, dups = set(), set()
seen = {}
for i, val1 in enumerate(nums):
if val1 not in dups:
dups.add(val1)
for j, val2 in enumerate(nums[i+1:]):
complement = -val1 - val2
if complement in seen and seen[complement] == i:
min_val = min((val1, val2, complement))
max_val = max((val1, val2, complement))
if (min_val, max_val) not in found:
found.add((min_val, max_val))
res.append([val1, val2, complement])
seen[val2] = i
return res
如果找到要放入结果列表的结果,您的while
循环将永远运行。 那是因为while
循环中的else
子句不会改变循环条件,所以它只会以相同的low
、 high
和i
值继续运行,直到你用完 memory 来存储它们。
我怀疑您想在将解决方案附加到结果后同时提高low
和high
:
while(low<high):
val = nums[low]+nums[high] + nums[i]
if(val < 0) or ((low < high) and nums[low] == nums[low+1]):
low = low + 1
elif( val > 0) or ((low < high) and nums[high] == nums[high-1]):
high = high - 1
else:
res.append( (nums[i], nums[low], nums[high]))
low = low + 1
high = high - 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.