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一个数组,一个是不断的插入,另外一个方法是交换的方式
    • 改掉自身不好的习惯。
  • 相关阅读:
    vim文本替换命令
    Python线程优先级队列(Queue)
    Python线程同步
    Python使用Threading模块创建线程
    Python的isdigit()和isalpha()
    python判断unicode是否是汉字,数字,英文,或者其他字符
    理解Python的With语句
    K-means聚类算法(转)
    先验概率、后验概率以及共轭先验(转)
    经典动态规划python实现
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4460227.html
Copyright © 2011-2022 走看看