Next Permutation
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
Solution
public class Solution {
public void nextPermutation(int[] nums) {
if (nums.length == 0 || nums.length == 1)
return;
int runner = nums.length - 1;
while (runner >0 && nums[runner-1] >= nums[runner]){
runner --;
}
if (runner == 0) {
Arrays.sort(nums);
return;
}
int runner2 = nums.length - 1;
while (nums[runner2] <= nums[runner-1]) {
runner2 --;
}
// exchange runner2 & runner -1
int temp = nums[runner2];
nums[runner2] = nums[runner-1];
nums[runner-1] = temp;
Arrays.sort(nums, runner, nums.length);
}
}