Skip to content

Commit 3975f44

Browse files
authored
Update 0031.下一个排列.md
完善python代码
1 parent 73d7e3f commit 3975f44

File tree

1 file changed

+19
-58
lines changed

1 file changed

+19
-58
lines changed

problems/0031.下一个排列.md

Lines changed: 19 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -160,73 +160,34 @@ class Solution {
160160
```
161161
162162
## Python
163-
>直接使用sorted()不符合题意
163+
>直接使用sorted()会开辟新的空间并返回一个新的list,故补充一个原地反转函数
164164
```python
165165
class Solution:
166166
def nextPermutation(self, nums: List[int]) -> None:
167167
"""
168168
Do not return anything, modify nums in-place instead.
169169
"""
170-
for i in range(len(nums)-1, -1, -1):
171-
for j in range(len(nums)-1, i, -1):
170+
length = len(nums)
171+
for i in range(length - 1, -1, -1):
172+
for j in range(length - 1, i, -1):
172173
if nums[j] > nums[i]:
173174
nums[j], nums[i] = nums[i], nums[j]
174-
nums[i+1:len(nums)] = sorted(nums[i+1:len(nums)])
175-
return
176-
nums.sort()
177-
```
178-
>另一种思路
179-
```python
180-
class Solution:
181-
'''
182-
抛砖引玉:因题目要求“必须原地修改,只允许使用额外常数空间”,python内置sorted函数以及数组切片+sort()无法使用。
183-
故选择另一种算法暂且提供一种python思路
184-
'''
185-
def nextPermutation(self, nums: List[int]) -> None:
186-
"""
187-
Do not return anything, modify nums in-place instead.
188-
"""
189-
length = len(nums)
190-
for i in range(length-1, 0, -1):
191-
if nums[i-1] < nums[i]:
192-
for j in range(length-1, 0, -1):
193-
if nums[j] > nums[i-1]:
194-
nums[i-1], nums[j] = nums[j], nums[i-1]
195-
break
196-
self.reverse(nums, i, length-1)
197-
break
198-
if n == 1:
199-
# 若正常结束循环,则对原数组直接翻转
200-
self.reverse(nums, 0, length-1)
201-
202-
def reverse(self, nums: List[int], low: int, high: int) -> None:
203-
while low < high:
204-
nums[low], nums[high] = nums[high], nums[low]
205-
low += 1
206-
high -= 1
207-
```
208-
>上一版本简化版
209-
```python
210-
class Solution(object):
211-
def nextPermutation(self, nums: List[int]) -> None:
212-
n = len(nums)
213-
i = n-2
214-
while i >= 0 and nums[i] >= nums[i+1]:
215-
i -= 1
216-
217-
if i > -1: // i==-1,不存在下一个更大的排列
218-
j = n-1
219-
while j >= 0 and nums[j] <= nums[i]:
220-
j -= 1
221-
nums[i], nums[j] = nums[j], nums[i]
175+
self.reverse(nums, i + 1, length - 1)
176+
return
177+
self.reverse(nums, 0, length - 1)
222178
223-
start, end = i+1, n-1
224-
while start < end:
225-
nums[start], nums[end] = nums[end], nums[start]
226-
start += 1
227-
end -= 1
228-
229-
return nums
179+
def reverse(self, nums: List[int], left: int, right: int) -> None:
180+
while left < right:
181+
nums[left], nums[right] = nums[right], nums[left]
182+
left += 1
183+
right -= 1
184+
185+
"""
186+
265 / 265 个通过测试用例
187+
状态:通过
188+
执行用时: 36 ms
189+
内存消耗: 14.9 MB
190+
"""
230191
```
231192

232193
## Go

0 commit comments

Comments
 (0)