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;
    }
};

 

转载于:https://www.cnblogs.com/jasonlixuetao/p/10925923.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值