Next Permutation解题报告

Description:

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.

Example:

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

Link:

https://leetcode.com/problems/next-permutation/#/description

解题方法:

从后往前找,找到第一个 nums[p] < nums[p+1]的数的位置p。
再次从后往前找,找到第一个nums[c] > nums[p]的数的位置c。
交换两个位置的数,再将p之后的数都反序。

Tips:

直接用reverse函数实现反序。

Time Complexity:

O(N)

完整代码:

void nextPermutation(vector& nums) 
    {
        int n = nums.size();
        if(n < 2)
            return;
        int p = n-1, c = n-1;
        while(p >= 0)
        {
            if(p != n-1 && nums[p] < nums[p+1])
                break;
            p--;
        }
        if(p < 0)
        {
            std::reverse(nums.begin(), nums.end());
            return;
        }
        while(c > 0)
        {
            if(nums[c] > nums[p])
                break;
            c--;
        }
        int temp = nums[p];
        nums[p] = nums[c];
        nums[c] = temp;

        std::reverse(nums.begin()+p+1, nums.end());
        return;
    }

你可能感兴趣的:(Next Permutation解题报告)