leetcode_1053. Previous Permutation With One Swap

Posted jasonlixuetao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode_1053. Previous Permutation With One Swap相关的知识,希望对你有一定的参考价值。

1053. Previous Permutation With One Swap

https://leetcode.com/problems/previous-permutation-with-one-swap/

题意:Given an array A of positive integers (not necessarily distinct), return the lexicographically largest permutation that is smaller than A, that can be made with one swap (A swap exchanges the positions of two numbers A[i] and A[j]).  If it cannot be done, then return the same array.


 

解法:对于每个A,找到最右边的第一个逆序对{ A[i]>A[j] },然后将A[i]和其后小于A[i]的最大的元素交换。

 

class Solution
{
public:
    vector<int> prevPermOpt1(vector<int>& A)
    {
        int pa=A.size()-2,mina=A[A.size()-1],pos=A.size()-1;
        while(pa>=0)
        {
            if(A[pa]>A[pa+1])
            {
                pos=pa;
                break;
            }
            pa--;
        }
        if(pos==A.size()-1)
            return A;
        int pos_=pos+1,maxa=-1,max_pos=-1;
        while(pos_<A.size())
        {
            if(A[pos_]<A[pos]&&A[pos_]>maxa)
            {
                maxa=A[pos_];
                max_pos=pos_;
            }
            pos_++;
        }
        swap(A[pos],A[max_pos]);
        return A;
    }
};

 

以上是关于leetcode_1053. Previous Permutation With One Swap的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 1053. Previous Permutation With One Swap

leetcode1053

数组旋转 Leetcode#189

BZOJ1053_反素数_KEY

[BZOJ1053][SDOI2005]反素数ant 数学

hiho_1053_居民迁移