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
如何得到下一个排列参见(http://www.cnblogs.com/grandyang/p/4428207.html)
解法
总体思路就是从后往前找,当第i+1个位大于第i位时,则要把第i位和其后面的数字中最小的一个大于它的数交换位置,然后将i+位之后的数从小到大排序
public void nextPermutation(int[] nums) {
int n=nums.length;
for( int i=n-2;i>=0;i--){
if(nums[i+1]>nums[i])
{
for(int j=n-1;j>i;j--){
if(nums[j]>nums[i])
{
int tmp=nums[j];
nums[j]=nums[i];
nums[i]=tmp;
Arrays.sort(nums, i+1, n);
return ;
}
}
}
}
Arrays.sort(nums);
}
Runtime: 7 ms, faster than 98.10% of Java online submissions for Next Permutation.
Memory Usage: 38.7 MB, less than 27.52% of Java online submissions for Next Permutation.