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 };
  • 相关阅读:
    swagger生成接口文档
    二分查找通用模板
    go-json技巧
    【Go】获取用户真实的ip地址
    数据库储存时间类型
    密码加密:md5/sha1 +盐值
    参数里时间格式的转换
    不好定位的元素定位
    vim编辑器
    ps -ef | grep php kill -9
  • 原文地址:https://www.cnblogs.com/chkkch/p/2787483.html
Copyright © 2011-2022 走看看