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;
                    }
                }
            }
        }
    };
    
  • 相关阅读:
    c# in deep 之LINQ简介(1)
    今天开通博客
    bzoj 4009 接水果 整体二分
    区间求mex的几种方法
    充分性,必要性,充分条件,必要条件的区别
    表达式求值(noip2015等价表达式)
    selenium-模拟鼠标
    selenium学习-ActionChains方法列表
    高手指导中手的书籍
    新生
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7822764.html
Copyright © 2011-2022 走看看