-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path31_Next_Permutation.py
More file actions
48 lines (40 loc) · 1.4 KB
/
Copy path31_Next_Permutation.py
File metadata and controls
48 lines (40 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
https://leetcode.com/problems/next-permutation/
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
"""
class Solution:
def nextPermutation(self, nums: 'List[int]') -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# 1. 从后往前遍历,找到第一个比后一个小的数字
e = len(nums)
l = len(nums)-2
while l>=0:
if nums[l] < nums[l+1]:
break
l-=1
if l == -1:
nums[:] = nums[::-1]
return
# 2. 将后面比这个数字大的第一个数字与这个数字交换
t = len(nums)-1
while nums[t]-nums[l]<=0:
t-=1
nums[l], nums[t] = nums[t], nums[l]
# 3。 之后将所有后边的数转置
l, r = l+1, e-1
while l<r:
nums[l], nums[r] = nums[r], nums[l]
l+=1
r-=1
x = Solution()
nums = [1,3,2]
x.nextPermutation(nums)
print(nums)