zoukankan      html  css  js  c++  java
  • 31. Next Permutation

    mplement 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 and use only constant 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,31,3,2
    3,2,11,2,3
    1,1,51,5,1

    思考:以1,3,2,5,4,3,1为例,从右向左,直到5依次递增,说明,相对大的数都已经放在相对大的权重,已经达到最大。再向左观察2,考察2,5,4,3,1。显然2这个位置可以放更大的数字以实现数的变大,找到2右边的最靠近2的比2大的数,3。所以应该是3代替2的位置,然后后面的这4个位置的数应该尽可能的小,即最大的数字在最低位,降序即可。

     1 class Solution {
     2 public:
     3     void nextPermutation(vector<int>& nums) {
     4         
     5         int len = nums.size();
     6         int index = len-2;
     7         while(index>=0 && nums[index]>=nums[index+1]) index--;
     8         
     9         if(index==-1) {sort(nums.begin(),nums.end()); return;}
    10         
    11         int index2 = len-1;
    12         while(nums[index2]<=nums[index]) index2--;
    13         
    14         swap(nums[index], nums[index2]);
    15         
    16         sort(nums.begin()+index+1,nums.end());
    17         
    18         
    19     }
    20 };
  • 相关阅读:
    input 正则
    .net ashx Session 未将对象引用到实例
    js 时间和时间对比
    c# Repeater 和 AspNetPager
    c#后台 极光推送到Android 和IOS客户端
    select scope_identity()
    redhat7.4安装git(按照官网从源码安装)
    redhat7.4安装gitlab
    ES6模板字符串
    初次接触webpack
  • 原文地址:https://www.cnblogs.com/midhillzhou/p/8991688.html
Copyright © 2011-2022 走看看