zoukankan      html  css  js  c++  java
  • Leetcode: 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.

    Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
    1,2,3 → 1,3,2
    3,2,1 → 1,2,3
    1,1,5 → 1,5,1

    思路

    1. 明说 in-place

    2. 先从后面的字符中找到一个较小的, 替代前面的某一个数字, 然后进行一次排序

    3. 参考别人的思路. (2) 大体上是对的, 但是细节没有分析. 正确的解法

      a) Find out the first ascending pair from the end of the list.
       Taking the list [2,3,1] as example, we found the 2<3.
       Assuming the index of first element as i, the latter as j. Each time when j=i+1, reset the j to the end of list and --i.
       Turn to step 4 if the pair not found.

      b) if i >= 0, swap the number at indexes i and j.
        After this done, the elements after i is also in descending order.

      c) Reverse the elements after i. And return

      d) If no ascending pair is found, that means the given list is well sorted in the descending order. In this case, just reverse the whole list as required in      this problem.

    Update

    1. 题目有递归性质, "从后面的字符中寻找较小的, 替代前面的某一个数字", 这句话本身就暗示着在找到那个 "较小" 的数字之前, 后面的那些字符必定是有序的. 同时, 寻找的比较过程也保证了, 替换元素后, 后面的字符必然是逆序排列的

    代码

    class Solution {
    public:
        void nextPermutation(vector<int> &num) {
            int i = num.size()-1;
            for(; i > 0; i --) {
                if(num[i] > num[i-1]) {
                    break;
                }
            }
    
            if(i == 0) {
                reverse(num.begin(), num.end());
            }else{
                int lt = i, j;
                for(j = i; j < num.size(); j++) {
                    if(num[j] <= num[i-1]) {
                        break;
                    }
                }
                swap(num[i-1], num[j-1]);
                sort(num.begin()+i, num.end());
            }
        }
    };

     

  • 相关阅读:
    Vue项目中全局过滤器的使用(格式化时间)
    vue-photo-preview 图片放大功能
    mongoimport导入json文件
    node后台,MongoDB作为数据库,vue前端获取数据并渲染
    JeasyUI,导出Excel
    EasyUI的textbox的disable ,readonly 用法
    EasyUI 中 Combobox里的onChange和onSelect事件的区别
    NullReferenceException 的可恨之处
    最新国家行政区划代码,来自国家统计局2018年底最新数据
    把旧系统迁移到.Net Core 2.0 日记 (20) --使用MiniProfiler for .NET
  • 原文地址:https://www.cnblogs.com/xinsheng/p/3515365.html
Copyright © 2011-2022 走看看