Description
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
31,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
Solution
Step 1: From the end, find the first element breaks the decsending sequence, which is the element need to be changed to a bigger because the decsending elements after it are already finished
Step 2: From the end, find the first element that bigger than the element found at step 1, which is the new elelment at the position of the step 1 emelemt. Swap them, which doesn’t change the decsending order of that sequence.
Step 3: Reverse the decsending sequence.
1 | class Solution { |