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
    

    Subscribe to see which companies asked this question.
    题目意思就是让你输出这个数列的下一个字典序大的排列, 如果它本身最大的话,输出最小的那个。

    • 检查一个是否本身最大, 不是的话直接next_permutation()。
    • 是的话直接把vector反转一下就是最小的了
    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            bool is = false;
            size_t sum = nums.size();
            for(size_t i = 0; i < sum-1; ++ i)
                if(nums[i] < nums[i+1])
                    is = true;
            if(is)
                next_permutation(nums.begin(), nums.end());
            else
            {
                size_t b = 0, e = sum - 1;
                while(b < e)
                    swap(nums[b++], nums[e--]);
            }
        }
    };
    
  • 相关阅读:
    通用二进制格式安装、编译安装过程(以mysql为例)
    linux:网络
    深圳:软通-运维
    深圳:软通-python
    linux:用户管理
    linux:vim
    深圳:卡莱特-售前/售后服务
    linux:基本指令
    linux:安装
    电脑:磁盘扩容
  • 原文地址:https://www.cnblogs.com/aiterator/p/6582052.html
Copyright © 2011-2022 走看看