36 lines
1.0 KiB
Python
36 lines
1.0 KiB
Python
|
class Solution:
|
||
|
def nextPermutation(self, nums: List[int]) -> None:
|
||
|
"""
|
||
|
Do not return anything, modify nums in-place instead.
|
||
|
"""
|
||
|
# Find start of strictly decreasing section from the right
|
||
|
# and identify the position of element right before it
|
||
|
|
||
|
right = len(nums) - 1
|
||
|
|
||
|
while right > 0:
|
||
|
if nums[right - 1] < nums[right]:
|
||
|
break
|
||
|
|
||
|
right -= 1
|
||
|
|
||
|
swap_pos = right - 1
|
||
|
|
||
|
# Array is already in decreasing order, hence we return the reverse
|
||
|
if swap_pos < 0:
|
||
|
nums.reverse()
|
||
|
return
|
||
|
|
||
|
# Find next greatest element from [swap_pos + 1, n)
|
||
|
right = len(nums) - 1
|
||
|
while right > swap_pos:
|
||
|
if nums[right] > nums[swap_pos]:
|
||
|
break
|
||
|
|
||
|
right -= 1
|
||
|
|
||
|
nums[swap_pos], nums[right] = nums[right], nums[swap_pos]
|
||
|
|
||
|
# Reverse [swap_pos + 1, n)
|
||
|
nums[swap_pos + 1:] = nums[:swap_pos:-1]
|