题目
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
意思就是数学中的排列组合,比如“1,2,3”的全排列,依次是:
从上面的某一行重排到期下一行,如果已经是最后一行了,则重排成第一行。
但是也不能根据给出的数组中的数字列出所有排列,因为要求不能占用额外的空间。
参考一个不错的讲解:点击打开链接
总结来说就是:如果所有数字依次递减,那就说明这是全排列中最大的序列了。如果不是的话,从末尾向前找第一个不满足的位置,并在其后找到比这个数字大的数字当中最小的那个和这个数字交换,然后把这个数字之后的所有数字进行递增排列。因为这道题目要求不能占用额外的空间,我一开始想到的使用冒泡排序,后来参考答案发现可以用Arrays.sort()函数。
public void nextPermutation(int[] nums) {
int i=nums.length-1;
for(;i>0;i--){
if(nums[i-1]<nums[i])
break;
}
if(i==0)
Arrays.sort(nums);
else{
int min = i;
for(int j=i;j<nums.length;j++){
if(nums[j]>nums[i-1]&&nums[j]<nums[min])
min = j;
}
int temp = nums[i-1];
nums[i-1] = nums[min];
nums[min] = temp;
Arrays.sort(nums,i,nums.length);
}
}