@@ -120,8 +120,50 @@ class Solution {
120
120
```
121
121
122
122
## 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
+ >另一种思路
124
139
```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
125
167
```
126
168
127
169
## Go
0 commit comments