在用Python刷LeedCode面试题49丑数时,遇到IndexError: list assignment index out of range 错误,下面介绍怎么解决。
class Solution:
def nthUglyNumber(self, n: int) -> int:
p2,p3,p5 = 0,0,0
dp = [1,]
i=1
while i!=n:
dp[i] = min(dp[p2] * 2,dp[p3] * 3,dp[p5] * 5)
if dp[i] == dp[p2] * 2: p2 += 1
if dp[i] == dp[p3] * 3: p3 += 1
if dp[i] == dp[p5] * 5: p5 += 1
i += 1
return dp[n-1]
出现IndexError: list assignment index out of range错误,原因是空数组不能直接指定位置。解决:‘
方法一,指定列表的长度:
class Solution:
def nthUglyNumber(self, n: int) -> int:
p2,p3,p5 = 0,0,0
dp = [0]*n
dp[0] = 1
i=1
while i!=n:
dp[i] = min(dp[p2] * 2,dp[p3] * 3,dp[p5] * 5)
if dp[i] == dp[p2] * 2: p2 += 1
if dp[i] == dp[p3] * 3: p3 += 1
if dp[i] == dp[p5] * 5: p5 += 1
i += 1
return dp[n-1]
方法二,用append():
class Solution:
def nthUglyNumber(self, n: int) -> int:
p2,p3,p5 = 0,0,0
dp = [1,]
i=1
while i!=n:
value = min(dp[p2] * 2,dp[p3] * 3,dp[p5] * 5)
dp.append(value)
if value == dp[p2] * 2: p2 += 1
if value == dp[p3] * 3: p3 += 1
if value == dp[p5] * 5: p5 += 1
i += 1
return dp[n-1]