Merge pull request #1631 from casnz1601/patch-24

Update 0031.下一个排列.md
This commit is contained in:
程序员Carl
2022-09-10 17:42:12 +08:00
committed by GitHub

View File

@ -160,73 +160,34 @@ class Solution {
``` ```
## Python ## Python
>直接使用sorted()不符合题意 >直接使用sorted()会开辟新的空间并返回一个新的list故补充一个原地反转函数
```python ```python
class Solution: class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in range(len(nums)-1, -1, -1):
for j in range(len(nums)-1, i, -1):
if nums[j] > nums[i]:
nums[j], nums[i] = nums[i], nums[j]
nums[i+1:len(nums)] = sorted(nums[i+1:len(nums)])
return
nums.sort()
```
>另一种思路
```python
class Solution:
'''
抛砖引玉因题目要求“必须原地修改只允许使用额外常数空间”python内置sorted函数以及数组切片+sort()无法使用。
故选择另一种算法暂且提供一种python思路
'''
def nextPermutation(self, nums: List[int]) -> None: def nextPermutation(self, nums: List[int]) -> None:
""" """
Do not return anything, modify nums in-place instead. Do not return anything, modify nums in-place instead.
""" """
length = len(nums) length = len(nums)
for i in range(length-1, 0, -1): for i in range(length - 1, -1, -1):
if nums[i-1] < nums[i]: for j in range(length - 1, i, -1):
for j in range(length-1, 0, -1): if nums[j] > nums[i]:
if nums[j] > nums[i-1]: nums[j], nums[i] = nums[i], nums[j]
nums[i-1], nums[j] = nums[j], nums[i-1] self.reverse(nums, i + 1, length - 1)
break return
self.reverse(nums, i, length-1) self.reverse(nums, 0, length - 1)
break
if n == 1:
# 若正常结束循环,则对原数组直接翻转
self.reverse(nums, 0, length-1)
def reverse(self, nums: List[int], low: int, high: int) -> None: def reverse(self, nums: List[int], left: int, right: int) -> None:
while low < high: while left < right:
nums[low], nums[high] = nums[high], nums[low] nums[left], nums[right] = nums[right], nums[left]
low += 1 left += 1
high -= 1 right -= 1
```
>上一版本简化版
```python
class Solution(object):
def nextPermutation(self, nums: List[int]) -> None:
n = len(nums)
i = n-2
while i >= 0 and nums[i] >= nums[i+1]:
i -= 1
if i > -1: // i==-1,不存在下一个更大的排列 """
j = n-1 265 / 265 个通过测试用例
while j >= 0 and nums[j] <= nums[i]: 状态:通过
j -= 1 执行用时: 36 ms
nums[i], nums[j] = nums[j], nums[i] 内存消耗: 14.9 MB
"""
start, end = i+1, n-1
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
return nums
``` ```
## Go ## Go