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一个数组,一个是不断的插入,另外一个方法是交换的方式
    • 改掉自身不好的习惯。
  • 相关阅读:
    Python基础教程:多线程运行带多个参数的函数
    Python基础教程:list相关操作
    python字典教程:setdefault方法和get方法
    Python 异常处理集合
    python基础教程:5个带key的python内置函数
    python操作Excel的5种方式
    Python3压缩和解压缩实现
    jenkins 分布式配置主从节点
    CentOS7 free字段含义
    nginx配置https
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4460227.html
Copyright © 2011-2022 走看看