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一个数组,一个是不断的插入,另外一个方法是交换的方式
    • 改掉自身不好的习惯。
  • 相关阅读:
    单点登陆的javascript类原创
    goole图标
    字符串string的相关应用
    今天心情好,发首我喜欢的歌天黑黑
    爱情幸福!
    linux虚拟实现
    页面显示的问题
    由我们MIS的老师,所引发的一点感想.
    有关PERL5和正则表达式
    本来没有什么好说的!
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4460227.html
Copyright © 2011-2022 走看看