我正在嘗試解決 Leetcode 問題:
實作下一個排列,將數字重新排列為按字典順序排列的下一個更大的數字排列。如果這樣的排列是不可能的,它必須將其重新排列為可能的最低順序(即按升序排序)。替換必須到位并且只使用恒定的額外記憶體。
我不明白為什么我在第 17 行收到一條錯誤訊息,提示“串列索引超出范圍”(我標記為“錯誤”)。測驗用例都在作業。
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
# pivot
r = len(nums) - 1
while nums[r-1] > nums[r] and r > 0:
r -= 1
pivot = r
if pivot == 0:
nums.sort()
return
# swap
else:
swap = len(nums) - 1
while nums[pivot-1] >= nums[swap]: # error (line 17)
swap -= 1
nums[pivot-1], nums[swap] = nums[swap], nums[pivot-1]
# reverse
nums[pivot:] = sorted(nums[pivot:])
uj5u.com熱心網友回復:
眼前的問題是,對于像 之類的輸入,swap可以變得小于,以防止這種變化:0[1, 1]
while nums[pivot-1] >= nums[swap]:
到:
while nums[pivot-1] >= nums[swap] and swap >= 0:
此外,您還希望在樞軸計算回圈中使用>=而不是使用>,這樣,當兩個相鄰元素相同(例如,[2, 1, 1])時,您不會過早退出回圈,即更改:
while nums[r-1] > nums[r] and r > 0:
到:
while nums[r-1] >= nums[r] and r > 0:
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/354370.html
下一篇:如何應用二分查找的主定理?
