LeetCode OJ-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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

大意:

数字串按照字典序排列,找出给出的数字串的下一个全排列。

思路:

见代码注释。

代码:

public class Solution {
    //按照字典序进行全排列
    //找全排列的下一个也就是找一个只比前一个数大,但比之后所有数小的排列
    //因为需要找仅比前一个排列大的数,所以从低位向高位替换
    //从最后一位向前看会有一个先升后降的规律出现(极端情况直接下降),替换首次下降的数字,极为i
    //并从之前上升的数列中找到比当前nums[i]大,且最接近nums[i]的值
    //找排列数的规律如下:
    //1.首先从后往前找到第一个下降的位置,记为i,如果没有则证明是最后一个排序,下一个为原串的逆序
    //2.从i往后,找到比i对应的数值大的当中最小的值对应的index
    //(由于后面都是降序的,所以找到第一个小于等于i对应的数值的前一个即为所求),如果没有则为length-1
    //3.交换nums[i] 和 nums[index]
    //4.将i后面的数字串逆序

    public void nextPermutation(int[] nums) {
        //i为数组的倒数第二个数
        int i = nums.length - 2;
        //从后向前找,找到第一次下降的位置
        while(i >= 0 && nums[i + 1] <= nums[i]) {
            i--;
        }
        int j = nums.length - 1;
        //从数组的最后向前找,找到第一次比i大的位置
        //因为数组是单调递增的,第一次比i大也就是比i大而且最接近i的数
        if(i >= 0) {
            while(j > 0 && nums[j] <= nums[i]) {
                j--;
            }
            swap(nums, i, j);       
        }
        reverse(nums, i + 1);
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    private void reverse(int[] nums, int start) {
        int i = start;
        int j = nums.length - 1;
        while(i < j) {
            swap(nums, i, j);
            i++;
            j--;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值