zoukankan      html  css  js  c++  java
  • 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

    下一个排列。c++stl中有个一个现成的算法,基本思路就是从后往前找到最大的排列a[i] a[i+1] ...a[n] ,什么是最大的排列呢,假设排列a0 a1 a2 a3 a4 a5,如果ao<a1 && a1 >=  a2 >= a3 >= a4 >=a5,那么a1 a2 a3 a4 a5就是最大的排列。同时最大排列代表的含义就是,以a[i-1]开头的排列已经排完了,下一个排列应该是从a[i] a[i+1]..a[n]中找到最小的大于a[i-1]的数,然后把其与a[i-1]交换一下,再把a[i] a[i+1]..a[n]反转就可以了。

    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            int numsSize = nums.size();
            int i=numsSize-1,j=i-1;
            while(j>=0 && nums[i]<= nums[j]){
                i=j;j-=1;
            }
            i = numsSize-1;
            cout<<"j="<<j<<endl;
            while(j>=0 && i>=0 && nums[i]<= nums[j]){
                i--;
            }
            cout<<"i="<<i<<endl;
            if(j>=0){
                swap(nums[i],nums[j]);
                reverse(nums.begin()+j+1,nums.end());
            }else{
                reverse(nums.begin(),nums.end());
            }
        }
    };
  • 相关阅读:
    监听器模式
    接口幂等性实现
    如何设计一个良好的API接口
    接口重试实现
    Spring不常用但有用的注解
    angular项目语言切换功能
    解决IOS上传竖向照片会旋转90度的问题
    微信点击链接:debugx5.qq.com提示您使用的不是x5内核
    swagger注释@API详细说明
    创建swap虚拟内存分区
  • 原文地址:https://www.cnblogs.com/zengzy/p/4964207.html
Copyright © 2011-2022 走看看