zoukankan      html  css  js  c++  java
  • Next Permutation

    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.

    思路:

    • 首先我们找到从尾部到头部第一个下降的digit. 在例子中是:2
    •  把从右到左第一个比dropindex大的元素换过来。
    •  把dropindex右边的的序列反序
    •  如果1步找不到这个index ,则不需要执行第二步。

    我的代码:

    public class Solution {
        public void nextPermutation(int[] num) {
            if(num==null || num.length<2) return;
            int i = num.length-2;
            int j = num.length-1;
            while(i >= 0)
            {
                if(num[i] < num[i+1]) break;
                i--;
            }
            if(i == -1)
            {
                reverseArray(num, 0, num.length-1);
                return;
            }
            while(j > i)
            {
                if(num[j] > num[i]) break;
                j--;
            }
            int tmp = num[i];
            num[i] = num[j];
            num[j] = tmp;
            reverseArray(num, i+1, num.length-1);
        }
        public void reverseArray(int[] num, int begin, int end)
        {
            while(begin < end)
            {
                int tmp = num[begin];
                num[begin] = num[end];
                num[end] = tmp;
                begin++;
                end--;
            }
        }
    }
    View Code

    学习之处:

    • 主要是如何生成顺序的permutation问题,这个是数学问题,之前学过,但是忘记了,差评
    • 如何reverse一个数组,一个是不断的插入,另外一个方法是交换的方式
    • 改掉自身不好的习惯。
  • 相关阅读:
    selenium-web自动化,常用api
    jmeter利用bean shell加密解密方法
    http请求属性说明(基础篇)
    移动端候选人面试要点
    CssSelector定位详解
    下载zip文件
    BeanShell生成随机中文字符
    BeanShell生成随机字符
    CentOS 7.2安装Oracle19C
    Centos7.4部署onlyoffice文档在线编辑服务器
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4460227.html
Copyright © 2011-2022 走看看