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

    本题是给了左边的一个排列,给出它的下一个排列。下一个排列是指按词典序的下一个排列。降序的排列已经是按词典序的最大的排列了,所以它的下一个就按升序排列。

    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]进行排序,从小到大。
    时间:16ms,代码如下:
    class Solution {
    public:
        void nextPermutation(vector<int> &num) {
            int end = num.size() - 1;
            int povit = end;
            while (povit){
                if (num[povit] > num[povit-1]) 
                    break;
                povit--;
            }
            if (povit > 0){
                povit--;
                int large = end;
                while (num[large] <= num[povit]) large--;
                swap(num[large], num[povit]);
                reverse(num.begin() + povit + 1, num.end());
            }
            else
                reverse(num.begin(), num.end());
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    Logger.getLogger与LogFactory.getLog
    log4j详解
    游戏史上80重要创新(原资料来自17173)
    软件开发工具介绍之 6.Web开发工具
    JAVA NIO 简介
    Alan Kay 你需要认识的一个天才
    大学计算机学习路线
    软件开发工具介绍之 5. 计划管理
    软件开发工具介绍之 4. 建模工具
    关于最近“361强奸360强奸QQ”,且是光天化日之下
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4576639.html
Copyright © 2011-2022 走看看