next permutation

Go Back home
 1 class Solution:
 2     def nextPermutation(self, nums):
 3         pivot = -1
 4         for i in reversed(range(1, len(nums))):
 5             if nums[i-1] < nums[i]:
 6                 pivot = i-1
 7                 break
 8         if pivot == -1:
 9             nums[:] = [*reversed(nums)]
10             return
11         for i in reversed(range(pivot, len(nums))):
12             if nums[i] > nums[pivot]:
13                 nums[i], nums[pivot] = nums[pivot], nums[i]
14         nums[pivot+1:] = reversed(nums[pivot+1:])
15 
16 nums = [2,4,5,3,1]
17 Solution().nextPermutation(nums)
18 assert nums == [2, 5, 1, 3, 4]
19 
20 nums = [1,2,3]
21 Solution().nextPermutation(nums)
22 assert nums == [1,3,2]
23 
24 nums = [3,2,1]
25 Solution().nextPermutation(nums)
26 assert nums == [1,2,3]
27 
28 nums = [1,1,5]
29 Solution().nextPermutation(nums)
30 assert nums == [1,5,1]