zoukankan      html  css  js  c++  java
  • 31.下一个排列

    题目描述:

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

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

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

      以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
        1,2,3 → 1,3,2
        3,2,1 → 1,2,3
        1,1,5 → 1,5,1

     解答:

    package array;
    
    public class L31 {
        public static void nextPermutation(int[] nums) {
            int i = nums.length-2;
            while(i>=0 && nums[i]>=nums[i+1]){
                i--;
            }
            if (i >= 0){
                int chanum = i+1;
                while(chanum<nums.length && nums[chanum]>nums[i]){
                    chanum++;
                }
                //更改channums位置的数字与i位置的数字
                swap(nums,chanum-1,i);
            }
            //需要将比i的索引大的数字全部进行翻转
            reverse(nums,i);
        }
        public static void swap(int[] nums,int locate1,int locate2){
            int temp = nums[locate1];
            nums[locate1] = nums[locate2];
            nums[locate2] = temp;
        }
        //由于nums中所有索引比start大的都是倒序的,所以此处只需要将该部分的数进行翻转
        public static void reverse(int[] nums,int start){
            int i = start+1,j = nums.length-1;
            while(i<j){
                swap(nums,i,j);
                i++;
                j--;
            }
        }
        public static void main(String[] args) {
            //[5,4,7,5,3,2]
            //[5,5,3,4,2,7]
            //预期结果
            //[5,5,2,3,4,7]
            int[] nums = new int[]{2,3,1};
            nextPermutation(nums);
            for(int index = 0;index<nums.length;index++){
                System.out.println(nums[index]);
            }
    
        }
    }
      执行用时 :1 ms, 在所有 java 提交中击败了100.00%的用户
      内存消耗 :36.5 MB, 在所有 java 提交中击败了89.88%的用户
  • 相关阅读:
    遍历当前窗口名字
    Delphi获取其它进程窗口句柄的3种方法
    Delphi判断一个字符是否为汉字的最佳方法
    Delphi拷贝目录(含子目录)的方法
    贴一份用delphi修改注册表改网卡MAC地址的代码
    delphi的TFileStream 内存流
    Delphi的ListView自动排序
    Delphi中上指定进程(进程名)
    Delphi-IP地址的隐藏
    C# 简单线程实例
  • 原文地址:https://www.cnblogs.com/mayang2465/p/11724609.html
Copyright © 2011-2022 走看看