zoukankan      html  css  js  c++  java
  • LeetCode——Next Permutation

    1. Question

    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

    2. Solution

    1. 从后往前,找第一个下降的数字nums[i] > nums[i - 1],如果没找到那么直接将数组反转即可。

    2. 再从后往前,找一个数nums[j] > nums[i - 1],交换他们两个数字,然后再将nums[i - 1]之后的数进行反转。

    3. 时间复杂度O(n)。

    3. Code

    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            int i = nums.size() - 1;
            for (; i > 0; i--) {   // 找第一个下降的位置
                if (nums[i] > nums[i - 1])
                    break;
            }
            if (i == -1 || i == 0) {
                reverse(nums.begin(), nums.end());
            } else {
                for (int j = nums.size() - 1; j >= 0; j--) {
                    if (nums[j] > nums[i - 1]) {  // 找第一个比下降位置数大的
                        swap(nums[j], nums[i - 1]);
                        reverse(nums.begin() + i, nums.end());   // 反转之后的数
                        break;
                    }
                }
            }
        }
    };
    
  • 相关阅读:
    idea常用快捷键
    Spring中<bean>标签之使用p标签配置bean的属性
    Mysql语句转义
    Idea使用(摘抄至java后端技术公众号-孤独烟)
    js中scroll滚动相关
    Flask-wtforms类似django中的form组件
    Flask中的数据连接池
    SQLAlchemy
    博客园美化阅读模式
    [NOIP2003] 提高组 洛谷P1039 侦探推理
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7822764.html
Copyright © 2011-2022 走看看