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. 使用STL中的库函数next_permutation,注意使用方法;
2. 查看《STL源码剖析》后,确认next_permutation的实现方式,手动实现之。即:
(1)从vector的后面找到第一个降序的数字,记录位置为pos;
(2)在vector的后半部分,即[v.begin()+pos+1, v.end()]区间,从后往前查找第一个比v[pos]大的数字,交换两个数的位置;
(3)然后对后半部分重新从小到大排序即可。
注意:如果此种排列为最大(后)一种,则下一种为最小(第一)种排列方式。

实现代码

1.
时间复杂度: O(n) 运行时间: 9ms

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        next_permutation(nums.begin(), nums.end());
    }
};

2.
使用sort排序时间复杂度: O(nlogn) 运行时间: 9ms
使用reverse时间复杂度: O(n) 运行时间: 9ms
明显后者时间上更优,但运行时间没有差别,想来可能是数据量比较小的原因。

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        if (nums.size() == 0) return;
        int firstMin = nums[nums.size() -1];
        int position = -1;
        for (int i = nums.size()-2; i >= 0; --i) {
            if (firstMin > nums[i]) {
                position = i;
                break;
            }
            else {
                firstMin = nums[i];
            }

        }
        if (position != -1) {
            for (int i = nums.size()-1; i >= position; --i) {
                if (nums[i] > nums[position]) {
                    int temp = nums[position];
                    nums[position] = nums[i];
                    nums[i] = temp;
                    break;
                }
            }
        }

        //sort(nums.begin() + position + 1, nums.end());
        reverse(nums.begin() + position + 1, nums.end());
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值