Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 75e1bb2

Browse files
authored
Update 0031.下一个排列.md
新增python代码: 抛砖引玉:因题目要求“必须原地修改,只允许使用额外常数空间”,python内置sorted函数以及数组切片+sort()无法使用,故选择另一种算法暂且提供一种python思路
1 parent 77c1098 commit 75e1bb2

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

problems/0031.下一个排列.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,33 @@ class Solution {
122122
## Python
123123

124124
```python
125+
class Solution:
126+
'''
127+
抛砖引玉:因题目要求“必须原地修改,只允许使用额外常数空间”,python内置sorted函数以及数组切片+sort()无法使用。
128+
故选择另一种算法暂且提供一种python思路
129+
'''
130+
def nextPermutation(self, nums: List[int]) -> None:
131+
"""
132+
Do not return anything, modify nums in-place instead.
133+
"""
134+
length = len(nums)
135+
for i in range(length-1, 0, -1):
136+
if nums[i-1] < nums[i]:
137+
for j in range(length-1, 0, -1):
138+
if nums[j] > nums[i-1]:
139+
nums[i-1], nums[j] = nums[j], nums[i-1]
140+
break
141+
self.reverse(nums, i, length-1)
142+
break
143+
else:
144+
# 若正常结束循环,则对原数组直接翻转
145+
self.reverse(nums, 0, length-1)
146+
147+
def reverse(self, nums: List[int], low: int, high: int) -> None:
148+
while low < high:
149+
nums[low], nums[high] = nums[high], nums[low]
150+
low += 1
151+
high -= 1
125152
```
126153

127154
## Go

0 commit comments

Comments
 (0)