31. Next Permutation
LeetCode 31. Next Permutation****
Description
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).
The replacement must be in place and use only constant extra memory.
Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100
Tags
Array
Solution
The basic idea is to find a permutation which is just larger than the current one but with the smallest possible gap.
We need to find the first two successive number nums[i]
and nums[j]
from the right, which satisfy nums[i] < nums[j]
. If no such pair, what should we do is just reverse the whole array, because it has already been the last permutation and we need to rearrange it as the lowest possible order.
Now, nums[j:]
is in descending order. We firstly find a position k where nums[k] > nums[i]
from the right. Secondly, swap the both. Lastly, reverse the nums[j:]
(which is still in descending order) to make the permutation as small as possible.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?