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--]);
            }
        }
    };
    
  • 相关阅读:
    Log4j学习
    HttpURLConnection请求
    正则表达式验证中文、图片上传
    freemarker学习
    参数中带有“&”符号问题
    禁止打印页面
    myEclipse 界面窗口打不开问题
    屏蔽网页右键
    分享功能
    table表格某一td内容太多导致样式混乱的解决方案
  • 原文地址:https://www.cnblogs.com/aiterator/p/6582052.html
Copyright © 2011-2022 走看看