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 1: use 1269753 as example, start from last number, moving ahead and find last num in increasing order. 126|9753: it is 9 in this case. Then sort from 9 to end. It became: 126|3579. Next step is to find the number just greater than 6 which is 7, swap them to be final answer: 1273569.
public class Solution {
public void nextPermutation(int[] nums) {
int n=nums.length;
if (n<=1) return;
int i=n-1;
while (i>0 && nums[i-1]>=nums[i]) i--;
Arrays.sort(nums,i,n);
if (i==0) return;
int j=i-1;
while (nums[i]<=nums[j]) i++;
int temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
}
没有评论:
发表评论