Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def nextPermutation(self, nums: List[int]) -> None:
- """
- Do not return anything, modify nums in-place instead.
- """
- def reverse(lo, hi, nums):
- while lo < hi:
- nums[lo], nums[hi] = nums[hi], nums[lo]
- lo += 1
- hi -= 1
- def swap(i, j, nums):
- nums[i], nums[j] = nums[j], nums[i]
- if len(nums) < 2:
- return
- # Find the first minimum from the right
- i = len(nums)-2
- while i >= 0 and nums[i+1] <= nums[i]:
- i -= 1
- # Find the smallest number that is larger than nums[i]
- if i >= 0:
- j = len(nums)-1
- while j >= 0 and nums[j] <= nums[i]:
- j -= 1
- # Swap the elements
- swap(i,j,nums)
- # Reverse elements
- reverse(i+1, len(nums)-1, nums)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement