[英]find triangular sum of an array (leetcode question)
https://leetcode.com/problems/find-triangular-sum-of-an-array/
所以我正在解決這個leetcode問題並提出了以下解決方案
class Solution:
def triangularSum(self, nums: List[int]) -> int:
arrLen = len(nums)
newArr = []
while len(nums) != 2:
for i in range(0, arrLen - 1):
total = (nums[i] + nums[i + 1])
total %= 10
newArr.append(total)
nums = newArr
arrLen = len(nums)
newArr = []
res = nums[0] + nums[1]
return res
所以它通過了測試用例,但是當我按下提交時,我得到一個 Time Limit Exceeded 錯誤。 詳細信息說,通過了 1 / 300 個測試用例。 狀態:超過時間限制。
我的算法做錯了嗎? 或者有什么方法可以讓它更快? 我真的迷路了
快速搜索“超過時間限制”和 leetcode 會得到以下結果: 在此處輸入鏈接描述
有了這些信息。
如果您的解決方案被判斷為超出時間限制,則可能是以下原因之一:
您的代碼有一個潛在的無限循環。 您的算法太慢並且時間復雜度很高。 您返回的數據結構處於無效狀態。 例如,包含循環的鏈表。
想想這三件事。
您可以通過使用列表推導來加快速度:
class Solution:
def triangularSum(self, nums: List[int]) -> int:
while len(nums) != 1:
nums = [(nums[i]+nums[i+1])%10 for i in range(len(nums)-1)]
return nums[0]
編輯:這是另一種絕對更快的方法:
class Solution:
def triangularSum(self, nums: List[int]) -> int:
# The idea of this is similar to the Pascal's triangle.
# If you deconstruct graph from the first example of [1, 2, 3, 4, 5] which is 48 -> 8
# The coefficient for each number is [1, 4, 6, 4, 1] which is equivalent of row (n-1) in Pascal's triangle
coefs = self.getRow(len(nums) - 1)
return sum(num*coef for num, coef in zip(nums, coefs))%10
@staticmethod
def getRow(rowIndex: int):
result = 1
yield result
for i in range(rowIndex, 0, -1):
result = result * i // (rowIndex+1-i)
yield result
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.