leetcode_1053. Previous Permutation With One Swap
2024-08-30 12:06:34
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()-,mina=A[A.size()-],pos=A.size()-;
while(pa>=)
{
if(A[pa]>A[pa+])
{
pos=pa;
break;
}
pa--;
}
if(pos==A.size()-)
return A;
int pos_=pos+,maxa=-,max_pos=-;
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;
}
};
最新文章
- 【耐克】【空军一号 Nike Air Force 1】【软木塞】
- 无法加载协定为xx的终结点配置部分,因为找到了该协定的多个终结点配置。请按名称指示首选的终结点配置部分。
- css样式注意
- POJ 1094 拓扑排序
- [博弈]ZOJ3591 Nim
- <;div>;相关
- codility上的练习(5)
- 幻世(OurDream)2D图形引擎使用教程8——处理操作输入(2)
- TypeScript设计模式之策略、模板方法
- JSP入门 taglib
- jmeter学习记录--07--jmeter元件
- 刷Python核心编程第三版的习题时遇到一个findall的坑
- 注入(injector)
- python3 练习题 day01
- python2和Python3的区别(长期更新)
- 【370】Python列表生成式(for 写入一行)
- CentOS7系统上部署.net core程序
- 2.1 The Object Model -- Classes and Instances(类和实例)
- HUE配置文件hue.ini 的liboozie和oozie模块详解(图文详解)(分HA集群)
- Spark Standalone Mode 多机启动 -- 分布式计算系统spark学习(二)(更新一键启动slavers)