zoukankan      html  css  js  c++  java
  • Next Permutation

    Question:

    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

    Solution:

     1 class Solution {
     2 public:
     3     void nextPermutation(vector<int>& nums) {
     4     int n=nums.size();
     5     int index=nums.size();
     6     for(int i=n-1;i>=1;i--)
     7     {
     8         if(nums[i]>nums[i-1])
     9         {
    10             index=i-1;
    11             break;
    12         }
    13     }
    14     if(index!=nums.size())
    15     {
    16         for(auto iter=nums.end()-1;iter>nums.begin()+index;iter--)
    17         {
    18             if(*iter>nums[index])
    19             {
    20                 int temp=nums[index];
    21                 *(nums.begin()+index)=*iter;
    22                 *iter=temp;
    23                 break;
    24             }
    25         }
    26         reverse(nums.begin()+index+1,nums.end());
    27     }
    28     else
    29         reverse(nums.begin(),nums.end());
    30         
    31     }
    32 };

  • 相关阅读:
    Unity 预处理命令
    Unity 2DSprite
    Unity 生命周期
    Unity 调用android插件
    Unity 关于属性的get/set
    代码的总体控制开关
    程序员怎么问问题?
    VCGLIB 的使用
    cuda实践(1)
    python之json文件解析
  • 原文地址:https://www.cnblogs.com/riden/p/4631534.html
Copyright © 2011-2022 走看看