public class Solution {
public void nextPermutation(int[] num) {
if(num.length < 2) {
return;
}
// Finds the start of descending sequence (consisting of last few elements)
int descStart = num.length - 1;
for(int i = num.length - 2; i >= 0 && num[i] >= num[i + 1]; i--) {
descStart = i;
}
// Reverses the descending sequence
for(int i = descStart; i < (descStart + num.length) / 2; i++) {
if(num[i] >= num[i + 1]) {
int tmp = num[i];
num[i] = num[num.length - i + descStart - 1];
num[num.length - i + descStart - 1] = tmp;
}
}
// Finds the first element in the descending sequence
// which is larger than the element right before descending sequence
if(descStart > 0) {
int initInd = descStart - 1;
int newInitInd = descStart;
while(newInitInd < num.length && num[initInd] >= num[newInitInd]) {
newInitInd++;
}
// Swapping
int tmp = num[initInd];
num[initInd] = num[newInitInd];
num[newInitInd] = tmp;
}
}
}
Time: O(n)
Space: O(1)