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 };
  • 相关阅读:
    【分区】使用 MBR 分区表分区并格式化
    微信小程序公司开发前必读
    Delphi 经典书籍
    sybase 通过select into创建新表
    sybase 创建触发器
    delphi 判断exe重复执行
    git 的诞生
    git 常用命令
    mvn spring-boot:run运行不了的解决办法
    git 提交代码
  • 原文地址:https://www.cnblogs.com/chkkch/p/2787483.html
Copyright © 2011-2022 走看看