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

最新文章

  1. 【耐克】【空军一号 Nike Air Force 1】【软木塞】
  2. 无法加载协定为xx的终结点配置部分,因为找到了该协定的多个终结点配置。请按名称指示首选的终结点配置部分。
  3. css样式注意
  4. POJ 1094 拓扑排序
  5. [博弈]ZOJ3591 Nim
  6. &lt;div&gt;相关
  7. codility上的练习(5)
  8. 幻世(OurDream)2D图形引擎使用教程8——处理操作输入(2)
  9. TypeScript设计模式之策略、模板方法
  10. JSP入门 taglib
  11. jmeter学习记录--07--jmeter元件
  12. 刷Python核心编程第三版的习题时遇到一个findall的坑
  13. 注入(injector)
  14. python3 练习题 day01
  15. python2和Python3的区别(长期更新)
  16. 【370】Python列表生成式(for 写入一行)
  17. CentOS7系统上部署.net core程序
  18. 2.1 The Object Model -- Classes and Instances(类和实例)
  19. HUE配置文件hue.ini 的liboozie和oozie模块详解(图文详解)(分HA集群)
  20. Spark Standalone Mode 多机启动 -- 分布式计算系统spark学习(二)(更新一键启动slavers)

热门文章

  1. sfc命令
  2. 用递归方式在JSON中查找对象
  3. 快速打开和关闭SQL服务
  4. Node.js学习(第四章:初见express)
  5. CodeForces 623B【预处理+DP】
  6. IT兄弟连 JavaWeb教程 Servlet会话跟踪 Session常用方法
  7. Spark 学习(三) maven 编译spark 源码
  8. Git - .gitignore怎么忽略已经被版本控制的文件
  9. Markdown - 如何使用上标、下标
  10. bio,nio,aio简介