feat(0031_next-permutation): add py3 soln
This commit is contained in:
35
0031_next-permutation/python3/solution.py
Normal file
35
0031_next-permutation/python3/solution.py
Normal 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]
|
||||
Reference in New Issue
Block a user