• 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 };
  • 相关阅读:
    动态tab页
    SQL Server附加数据库拒绝访问
    SQL window身份登陆 SQL server不能登陆
    SQL UPDATE 经典
    Char Varchar Nvarchar区别
    【OpenSSL】创建证书
    makecert 制作数字证书
    cer, pfx 创建,并且读取公钥/密钥,加解密 (C#程序实现)
    CompareValidator ASP控件
    XMLHelper 类
  • 原文地址:https://www.cnblogs.com/midhillzhou/p/8991688.html
Copyright © 2020-2023  润新知