zoukankan      html  css  js  c++  java
  • [LeetCode] 31. 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 // refer to http://bangbingsyb.blogspot.com/search?q=Next+Permutation
     2 class Solution {
     3 public:
     4     void nextPermutation(vector<int>& nums) {
     5         int i = 0, j = 0;
     6         
     7         if (nums.size() <= 1) return;
     8         
     9         for (i = nums.size() - 2; i >= 0; i--){
    10             if (nums[i] < nums[i+1]){
    11                 break;
    12             }
    13         }
    14         
    15         if (i < 0) {
    16             sort(nums.begin(), nums.end());
    17             return;
    18         }
    19         
    20         j = i + 1;
    21         while (j < nums.size() && nums[j] > nums[i]) j++;
    22         j--;
    23         
    24         swap(nums[i], nums[j]);
    25         sort(nums.begin() + i + 1, nums.end());
    26         
    27         return;
    28     }
    29 };
  • 相关阅读:
    Entity Framework在WCF中序列化的问题
    OTS
    ClickHouse原理解析与应用实践--摘录
    在docker中安装ogg19
    性能测试指标记录
    docker安装oracle12c记录
    docker安装oracle19c记录
    kudu
    stm32模拟iic从机程序
    STM32启动代码注释
  • 原文地址:https://www.cnblogs.com/amadis/p/6707902.html
Copyright © 2011-2022 走看看