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
Analysis
The steps to solve this problem:
1) scan from right to left, find the first element that is less than its previous one.
4 5 6 3 2 1 | p
2) scan from right to left, find the first element that is greater than p.
4 5 6 3 2 1 | q
3) swap p and q
4 5 6 3 2 1 swap 4 6 5 3 2 1
4) reverse elements [p+1, nums.length]
4 6 1 2 3 5
Java Solution
public void nextPermutation(int[] nums) { //find first decreasing digit int mark = -1; for (int i = nums.length - 1; i > 0; i--) { if (nums[i] > nums[i - 1]) { mark = i - 1; break; } } if (mark == -1) { reverse(nums, 0, nums.length - 1); return; } int idx = nums.length-1; for (int i = nums.length-1; i >= mark+1; i--) { if (nums[i] > nums[mark]) { idx = i; break; } } swap(nums, mark, idx); reverse(nums, mark + 1, nums.length - 1); } private void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } private void reverse(int[] nums, int i, int j) { while (i < j) { swap(nums, i, j); i++; j--; } } |
if(p<nums.length-1){
reverse(nums, p+1, nums.length-1);
} — here there is no need to check if p<nums.length -1.. p max value can be only nums.length -2 only
we go from right to left until numbers are in reverse.hence no need to sort and you only need to reverse.
does not work for 2 2 7 5 4 3 2 2 1. numbers after p + 1 should be put in ascending order.
Cool solution. I had the similar thought, but I wasn’t able to think of the second pass.