31. 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,31,3,2
3,2,11,2,3
1,1,51,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);
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值