[英]“Time Limit Exceeded” on LeetCode's three-sum problem?
我正在嘗試解決LeetCode的三和問題 ,我相信已經提出了O ( n ^ 2)個提交,但是我一直遇到“超過時限”錯誤。
例如,使用itertools.combinations
此解決方案:
from itertools import combinations
class Solution:
def threeSum(self, nums):
results = [triplet for triplet in combinations(nums, 3) if sum(triplet) == 0]
return [list(result) for result in set([tuple(sorted(res)) for res in results])]
導致以下錯誤:
同樣,此解決方案
from itertools import combinations
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
_map = self.get_map(nums)
results = set()
for i, j in combinations(range(len(nums)), 2):
target = -nums[i] - nums[j]
if target in _map and _map[target] and _map[target] - set([i, j]):
results.add(tuple(sorted([target, nums[i], nums[j]])))
return [list(result) for result in results]
@staticmethod
def get_map(nums):
_map = {}
for index, num in enumerate(nums):
if num in _map:
_map[num].add(index)
else:
_map[num] = set([index])
return _map
對於由一長串零組成的輸入產生“超出時間限制”:
之前曾有人問過這個問題( 優化對三和的解決方案 ),但是我正在尋找與這些解決方案有關的建議。 知道讓LeetCode解決方案“太慢”的原因是什么?
更新資料
在我看來,確定_map[target] - set([i, j])
-也就是說,當前的索引集是否也不是目標值的索引-可能會很昂貴,因此我應該首先查看是否對應的數字對是否存在。 所以我嘗試了這個:
from itertools import combinations
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
_map = self.get_map(nums)
results = set()
seen = set()
for i, j in combinations(range(len(nums)), 2):
target = -nums[i] - nums[j]
pair = tuple(sorted([nums[i], nums[j]]))
if target in _map and pair not in seen and _map[target] - set([i, j]):
seen.add(pair)
results.add(tuple(sorted([target, nums[i], nums[j]])))
return [list(result) for result in results]
@staticmethod
def get_map(nums):
_map = {}
for index, num in enumerate(nums):
if num in _map:
_map[num].add(index)
else:
_map[num] = set([index])
return _map
但是,這在輸入數量較大的另一個測試用例上失敗了:
這對我有用,對許多重復元素使用了一些優化。 我們存儲每個元素的外觀計數,然后僅迭代每個不同的元素。 其余的與您已經完成的類似
from collections import Counter
import itertools
class Solution:
def threeSum(self, nums):
counts = Counter(nums)
numSet = list(set(nums))
result = set()
for idx, num1 in enumerate(numSet):
for idx2, num2 in enumerate(itertools.islice(numSet, idx, None), start=idx):
num3 = (num1 + num2) * -1
if num3 in counts:
d = Counter([num1, num2, num3])
if not any(d[n] > counts[n] for n in d):
result.add(tuple(sorted([num1, num2, num3])))
return list(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.