[LeetCode] 031. Next Permutation
-
date_range April 02, 2019 - Tuesday info
Problem (Medium)
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
Approach 1:
Idea
The following gif makes a good explanation of the idea:
Solution
class Solution1:
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
for i in range(len(nums)-1):
if nums[-i-2] < nums[-i-1]:
ct = 1
while nums[-i-2] < nums[-i-2+ct] and -i-2+ct < 0:
ct += 1
ct -= 1
nums[-i-2], nums[-i-2+ct] = nums[-i-2+ct], nums[-i-2]
nums[-i-1:] = sorted(nums[-i-1:])
return
return nums.sort()
Complexity
- Time: $O(n)$
- Space: $O(1)$
KF