31. Next Permutation

题目: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 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

题意解析:

实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。

如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。

必须原地修改,只允许使用额外常数空间。

解题思路一:

根据题意找出比当前大的下一个排列,那么很明显这里需要从后面向前面遍历,从倒数第二个数字开始,依次与它的后面的一个数字进行比较,直到找到一个数字它的后面的数字比它大,此时当前的数字索引为j,然后我们从数组的最后一项开始向j进行遍历,直到找到一个数字比j位置的数字要大,此时将该数字与j位置的数字进行交换,最后让j+1一直到最后的数字进行首尾交换即可。如果一直遍历完也没有找到一个后面数字比前面大的,那么此时的数组就是逆序的,我们只需将数组进行反转即可。如数组{4,3,6,5,2},首先我们从后向前遍历直到3这个位置的时候才找到3<6,然后又从2向前找,直到找到一个比3大的数字,我们找到了5,就让5和3交换位置,此时数组变成了{4,5,6,3,2},然后就是让5后面的所有元素进行首尾交换,将小的数字移动到前面来。最后就得到了我们的结果{4,5,2,3,6}。

public void nextPermutation(int[] nums) {
        if(nums == null || nums.length == 0) return;
        for(int j = nums.length - 2;j>= 0;j--){
            if(nums[j] < nums[j+1]){                            
                for(int k = nums.length - 1;j<k;k--){
                    if(nums[j] < nums[k]){                      
                        int temp = nums[k];
                        nums[k] = nums[j];
                        nums[j] = temp;
                        break;
                    }
                }
                reverseArray(nums,j+1,nums.length - 1);         
                return;
            }
        }
        reverseArray(nums,0,nums.length - 1);                   
    }
    private void reverseArray(int[] nums, int begin, int end){
        for(int i = begin, j = end;i<j;i++,j--){
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }

提交代码之后:

Runtime: 1 ms, faster than 99.43% of Java online submissions for Next Permutation.

Memory Usage: 37.4 MB, less than 98.46% of Java online submissions for Next Permutation.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值