• 31. Next Permutation (java 字典序生成下一个排列)


    题目:

    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)从后向前遍历,找到第一个不满足降序的元素;若初始序列全部是降序,则i为-1,直接跳转至(3);

    (2)将该元素同它后面的元素中比它大的第一个元素交换;

    (3)将该元素后的所有元素排列,使之成为最小的排列。

    代码:

        public void nextPermutation(int[] nums) {
            if(nums == null || nums.length == 0)
                return;
            //长度为1的数组
            if (nums.length == 1) {
                return;
            }
        
            //从后向前找到第一个不满足逆序的元素
            int i = nums.length - 2; 
            for(; i >= 0 && nums[i] >= nums[i + 1]; --i); //注意,这里有=,可以排除含有重复元素的情况
            
            //从i+1位置开始,向后查找比nums[i]大的最小元素
            if(i >= 0){ 
                int j = i + 1;
                for(; j < nums.length && nums[j] > nums[i]; ++j);
                swap(nums,i,j - 1); //交换,注意是同 j - 1交换
            }
            
            //将i之后的元素逆置(这里包含一种特殊情况,若该排列已经是字典序中的最大了,则下一个序列应该是最小字典序,因此,直接在这里逆置即可)
            int k = nums.length - 1;
            i++;
            for(; i < k; i++, k--)
                swap(nums, i, k);
        }
        
        /**
         * 交换元素
         * @param array
         * @param i
         * @param j
         */
        public void swap(int[] array,int i ,int j){
            //交换
            int tmp = array[i];
            array[i] = array[j];
            array[j] = tmp;
        }
  • 相关阅读:
    Oracle 11G单机 无网络环境静默安装
    Centos 7 编译安装llvm 8.0.0
    linux下测试读写
    Linux 初始化 init 系统(1):sysvinit
    自动挂载文件/etc/fstab功能详解
    虚拟机安装LINUX网络配置注意的问题
    rhel7报错整理
    16/4/4二代支付硬盘故障处理
    RedHat Enterprise Linux 7关闭防火墙方法
    Linux命令之awk数组使用范例
  • 原文地址:https://www.cnblogs.com/mydesky2012/p/5620006.html
Copyright © 2020-2023  润新知