-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path31. Next Permutation.py
38 lines (37 loc) · 1021 Bytes
/
31. Next Permutation.py
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
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if len(nums) == 0:
return []
ans_a = -1
ans_b = -1
a = 0
b = 0
for i in range(1,len(nums)):
last = nums[a]
cur = nums[i]
if cur <= last:
a = i
elif cur > last:
if cur > nums[b] and b > a:
a = b
b = i
ans_a = a
ans_b = b
if ans_a != -1:
tmp = nums[ans_a]
nums[ans_a] = nums[ans_b]
nums[ans_b] = tmp
tmp = nums[ans_a + 1:len(nums)]
tmp.sort()
nums[ans_a + 1:len(nums)] = tmp
else:
nums.reverse()
return nums
if __name__ == "__main__":
solution = Solution()
re = solution.nextPermutation([2,1,3])
print re