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, do not allocate 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
10/31
My solution:
three example cases:
- [1,2,3,4] => [1,2,4,3]
- [1,2,4,3] =>[1,3,2,4]
- [4,3,2,1] => [1,2,3,4]
Step 1: find the largest i s.t. A[i] < A[i+1] by scanning backwards
in case 1, i = 2
in case 2, i = 1
in case 3, no such i, i.e. i = -1 < 0
After doing this, note that A[i+1~len-1] are in the descending order.
Step 2: if i < 0, then simply return A in ascending order (no need to sort, just reverse)
that is case 3, which is already the maximum
Step 3: if i >= 0, then sort A[i+1, len] (again no need to sort but simply reverse) and then swap i and j, where A[j] is the first element s.t. A[j] > A[i] and j > i
<pre name="code" class="java">public class Solution {
public void nextPermutation(int[] A) {
int len = A.length;
// step 1: scan backwards to find i s.t. A[i] < A[i+1]
int i = len-2;
while(i >= 0){
if(A[i] < A[i+1]) break;
else i--; // err1: forget about this
}
if(i < 0){
// A[i] >= A[i+1] for all i
reverse(A,0, len-1);
return;
}
// note that A[i] < A[i+1]
reverse(A,i+1, len-1);
// swap A[i] with A[j] with the first A[j] > A[i] s.t. j>i
for(int j=i+1; j<len; j++){
if(A[j] > A[i]){
swap(A,i,j);
break; // err2: forget to break
}
}
}
private void reverse(int[] A, int from, int to){
int start = from, end = to;
while(start < end){
swap(A, start, end);
start++;
end--;
}
}
private void swap(int[] A, int i, int j){
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
Time complexity: O(n), find i, reverse and swap
Space complexity is O(1)