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

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

  • 相关阅读:
    Javascript函数声明和函数表达式
    浅谈getAttribute兼容性
    js数组去重的三种常用方法总结
    说说JSON和JSONP,也许你会豁然开朗
    web安全之跨站请求伪造
    javascript中对象的深度克隆
    三种方式实现元素水平居中显示与固定布局和流式布局概念理解
    js dom element 属性整理(原创)
    ul下的li浮动,如何是ul有li的高度
    js数组去重的4个方法
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4042071.html
Copyright © 2011-2022 走看看