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 bool comp(const int &a, const int &b)
     2 {
     3     return a > b;
     4 };
     5 
     6 class Solution {
     7 public:
     8     void nextPermutation(vector<int> &num) {
     9         // Start typing your C/C++ solution below
    10         // DO NOT write int main() function
    11         int i;
    12         vector<int>::iterator iter = num.end();
    13         int maxNum = INT_MIN;
    14         for(i = num.size() - 1; i >= 0; i--)
    15         {
    16             iter--;
    17             if (num[i] < maxNum)
    18                 break;
    19             maxNum = max(maxNum, num[i]);                
    20         }
    21                 
    22         if (i >= 0)
    23         {
    24             int k;
    25             int minNum = INT_MAX;
    26             for(int j = i + 1; j < num.size(); j++)
    27                 if (num[j] > num[i] && num[j] < minNum)
    28                 {
    29                     minNum = num[j];
    30                     k = j;
    31                 }
    32             int t = num[i];
    33             num[i] = num[k];
    34             num[k] = t;    
    35             sort(iter + 1, num.end());
    36         }
    37         else
    38             sort(num.begin(), num.end());            
    39     }
    40 };
  • 相关阅读:
    序列化注意事项
    HTML5的新结构标签
    MVC模型
    CSS选择器权重计算规则
    HTML常用布局
    盒模型
    Spring Security 学习笔记-session并发控制
    java实例之随机点名
    java之方法重载
    java之方法
  • 原文地址:https://www.cnblogs.com/chkkch/p/2787483.html
Copyright © 2011-2022 走看看