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 };
  • 相关阅读:
    前端开发常用工具
    Promise和setTimeout执行顺序
    化生汤
    与vue+element相对于的组合
    脾胃笔记
    中医脉象
    javacript 面向对象
    fabric 安装及使用
    jquery.tablesorter.js 学习笔记
    iframe 标签自适应高度和宽度
  • 原文地址:https://www.cnblogs.com/midhillzhou/p/8991688.html
Copyright © 2011-2022 走看看