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
Solution:
We can provide several examples to find out how to get next permutation.
123413 -> 123431
1234852 -> 1235248
We can find out that there are consecutive numbers with descending order around tail, say 852, so there is a point with maximum number, it would be 8 in this case. In order to find the next permutation, we need to find a number (for example k)in the descending order consectutive numbers which is just greater than the number(for example j) right before maximum point, 4 in this case, and swap k with j. After swap them, the number starting from maximum point is still in descending order (think about it). Then arrange the new descending order numbers starting from maximum point to accending order.
Time complexity: O(n)
Code: beat 90.99%
public void nextPermutation(int[] nums) {
if (nums == null || nums.length == 0) {
return;
}
int indexMax = nums.length - 1;
while (indexMax > 0 && nums[indexMax] <= nums[indexMax - 1]) {
indexMax--;
}
if (indexMax == 0) {
reverse(nums, 0);
return;
}
int j = nums.length - 1;
while (j >= indexMax && nums[j] <= nums[indexMax - 1]){
j--;
}
swap(nums, j, indexMax - 1);
reverse(nums, indexMax);
return;
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
private void reverse(int[] nums, int start) {
int i = start, j = nums.length - 1;
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}