feat(0031_next-permutation): add py3 soln

This commit is contained in:
2022-04-05 21:59:48 +05:30
parent 27ed30d2a9
commit 65c530be33
2 changed files with 71 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
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]