python - Leetcode 31. 下一个排列 - Python
问题描述
我正在尝试解决一个 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:])
解决方案
直接的问题是,对于像这样的输入,它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:
推荐阅读
- javascript - Esprima 获取函数和变量声明
- java - java - 如何使用selenium java中的assert检查产品的价格是否在给定范围内
- python - 如何删除带有不均匀数字的空 matplotlib AxesGrid 单元格?
- r - 在 R 中使用 ggplot() 时,函数 scale_size_manual() 不会影响点的大小
- javascript - 如何修复“XML 解析错误:文档元素后的数据无法理解”?
- reactjs - 访问注入孙子组件的数据
- optimization - 如何在要最小化的 Numpy 产品中使用 CVX 变量?
- php - 包括大量的全局/常量变量
- javascript - 在 JQuery 中提交构造的表单时出现错误 403
- android - 无法从 Google Play 获取所有有效订阅