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,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
思路:According to Wikipedia, a man named Narayana Pandita presented the following simple algorithm to solve this problem in the 14th century.
- Find the largest index
k
such thatnums[i] < nums[i + 1]
. If no such index exists, just reversenums
and done. - Find the largest index j
> i
such thatnums[i] < nums[j]
. - Swap
nums[i]
andnums[j]
. - Reverse the sub-array
nums[i + 1 ~ n - 1]
.
class Solution {
public void nextPermutation(int[] nums) {
int n = nums.length;
int i = n - 2;
for(; i >= 0; i--) {
if(nums[i] < nums[i + 1]) {
break;
}
}
if(i < 0) {
reverse(nums, 0, n - 1);
return;
}
int j = n - 1;
while(j > i) {
if(nums[j] > nums[i]) {
break;
} else {
j--;
}
}
swap(nums, i, j);
reverse(nums, i + 1, n - 1);
}
private void swap(int[] A, int i, int j) {
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
private void reverse(int[] A, int start, int end) {
while(start <= end) {
swap(A, start, end);
start++;
end--;
}
}
}