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

Commit 6d02acc

Browse files
Merge pull request youngyangyang04#864 from casnz1601/patch-22
Update 0031.下一个排列.md
2 parents ecb4292 + 1598341 commit 6d02acc

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

problems/0031.下一个排列.md

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,8 +120,50 @@ class Solution {
120120
```
121121

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

127169
## Go

0 commit comments

Comments
 (0)