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;
        }
    };

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

  • 相关阅读:
    Flex 布局
    vue学习之用 Vue.js + Vue Router 创建单页应用的几个步骤
    vue学习起步:了解下
    vue学习一:新建或打开vue项目(vue-cli2)
    adb环境变量配置
    数据类型判断和数据类型转换代码工具
    日期工具集合
    postman变量的使用和设置
    浮点数运算和金额处理
    07- Linux常用命令
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4042071.html
Copyright © 2011-2022 走看看