The idea below is based on current sequence, set two pointers: first is for the current lower, and second is based on first, called next higher. If the entire sequence is descending, reverse the entire String… otherwise reverse the current lower and next higher, then reverse from the digit after current lower to the end of the String.
public class Solution {
public void nextPermutation(int[] num) {
if(num == null || num.length == 0){
return;
}
if(num.length == 1){
return;
}
int curLower = -1;
for(int i = 0; i < num.length - 1; i++){
if(num[i] < num[i + 1]){
curLower = i;
}
}
if(curLower == -1){
reverse(num, 0, num.length);
return;
}
int j = curLower;
int curHigher = curLower + 1;
while(j < num.length){
if(num[j] > num[curLower]){
curHigher = j;
}
j++;
}
int temp = num[curLower];
num[curLower] = num[curHigher];
num[curHigher] = temp;
reverse(num, curLower + 1, num.length);
}
private void reverse(int[] num, int s, int e){
int start = s;
int end = e - 1;
while(start < end){
int temp = num[start];
num[start] = num[end];
num[end] = temp;
start++;
end--;
}
}
}
没有评论:
发表评论