zoukankan      html  css  js  c++  java
  • leetcode第30题--Next Permutation

    problem:

    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.从后往前,找到第一个 A[i-1] < A[i]的。
    2.从 A[i]到A[n-1]中找到一个比A[i-1]大的最小值(也就是说在A[i]到A[n-1]的值中找到比A[i-1]大的集合中的最小的一个值)
    3.交换这两个值(A[i]和找到的值),并且把A[i]到A[n-1]进行排序,从小到大。
    这样就是词典序的下一个排列了。
    class Solution {
    public:
        void nextPermutation(vector<int> &num) {
            if (num.size() == 0)
                return;
            int ind = -1;
            for (int i = num.size() - 1; i > 0; i--) // 是大于零或者大于等于1
            {
                if (num[i - 1] < num[i])
                    {ind = i -1;break;}
            }
            if (ind == -1)
                {sort(num.begin(),num.end());return;}
            int min = INT_MAX, sw = -1;
            for (int j = num.size() -1; j > ind; j--)
            {
                if(num[j] > num[ind] && num[j] < min)
                    {   min = num[j]; sw = j;}
            }
            int tmp = num[ind];
            num[ind] = num[sw];
            num[sw] = tmp;
            vector<int>::iterator it = num.begin();
            for(int i = 0; i < ind + 1; i++)
            {
                it++;
            }
            sort(it, num.end());
            return;
        }
    };

    这题考察什么是词典序的下一个排列。

  • 相关阅读:
    php将字符串形式的数组转化为真数组
    Mysql8.0及以上 only_full_group_by以及其他关于sql_mode原因报错详细解决方案
    php使用base64_encode和base64_decode对数据进行编码和解码
    大数据基本概念
    sonarqube安装部署
    git-修改commit信息
    NLP-Commen Sense
    索引生命周期的管理
    kibana软件具体参数配置信息
    es机器监控x-pack导致的监控存储过大的问题
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4042071.html
Copyright © 2011-2022 走看看