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--]);
            }
        }
    };
    
  • 相关阅读:
    基本内置类型
    多维数组
    数组
    迭代器
    标准库类型 vector
    标准库类型 string
    运算符优先级表
    类型转换
    sizeof 和逗号运算符
    位运算符
  • 原文地址:https://www.cnblogs.com/aiterator/p/6582052.html
Copyright © 2011-2022 走看看