mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
@ -120,8 +120,50 @@ class Solution {
|
||||
```
|
||||
|
||||
## Python
|
||||
|
||||
>直接使用sorted()不符合题意
|
||||
```python
|
||||
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:
|
||||
"""
|
||||
Do not return anything, modify nums in-place instead.
|
||||
"""
|
||||
length = len(nums)
|
||||
for i in range(length-1, 0, -1):
|
||||
if nums[i-1] < nums[i]:
|
||||
for j in range(length-1, 0, -1):
|
||||
if nums[j] > nums[i-1]:
|
||||
nums[i-1], nums[j] = nums[j], nums[i-1]
|
||||
break
|
||||
self.reverse(nums, i, length-1)
|
||||
break
|
||||
else:
|
||||
# 若正常结束循环,则对原数组直接翻转
|
||||
self.reverse(nums, 0, length-1)
|
||||
|
||||
def reverse(self, nums: List[int], low: int, high: int) -> None:
|
||||
while low < high:
|
||||
nums[low], nums[high] = nums[high], nums[low]
|
||||
low += 1
|
||||
high -= 1
|
||||
```
|
||||
|
||||
## Go
|
||||
|
Reference in New Issue
Block a user