当前位置:网站首页>LeetCode 456. 132模式 单调栈/medium
LeetCode 456. 132模式 单调栈/medium
2022-07-27 14:05:00 【押切徹】
1.Description
给你一个整数数组 nums ,数组中共有 n 个整数。132 模式的子序列 由三个整数 nums[i]、nums[j] 和 nums[k] 组成,并同时满足:i < j < k 和 nums[i] < nums[k] < nums[j] 。
如果 nums 中存在 132 模式的子序列 ,返回 true ;否则,返回 false 。
2.Example
输入:nums = [3,1,4,2]
输出:true
解释:序列中有 1 个 132 模式的子序列: [1, 4, 2] 。
3.Solution
维护一个单调栈(从栈顶到栈底是单调递增或单调递减的,这里从栈顶到栈底是递增的),使k一直为次小值,当找到一个比次小值k还小的数时说明有了答案。
public boolean find132pattern(int[] nums) {
Deque<Integer> stack = new ArrayDeque<Integer>();
int n = nums.length;
if(n<3) {
return false;
}
int k = -1000000000;
for(int i=n-1;i>=0;i--) {
//当找到比次小值k小的数的时候,说明找到了i(k是次小的,栈里一定都是比k大的)
if(nums[i]<k) {
return true;
}
//栈里都是从i到数组尾中比k大的元素(且在栈中为递减顺序),当遇到比栈顶元素大时,维护k为次小值,将栈顶元素赋给k后在加入元素。
while(!stack.isEmpty()&&stack.peekLast()<nums[i]) {
k = stack.removeLast();
}
stack.addLast(nums[i]);
}
return false;
}
边栏推荐
- 国信证券手机开户安全吗 中山证券靠谱吗
- How to deploy open source Siyuan privately
- 网络设备硬核技术内幕 路由器篇 13 从鹿由器到路由器(上)
- 2022年中国网络视频市场年度综合分析
- Toward Fast, Flexible, and Robust Low-Light Image Enhancement(实现快速、灵活和稳健的弱光图像增强)CVPR2022
- Passive income: return to the original and safe two ways to earn
- 网络设备硬核技术内幕 路由器篇 18 DPDK及其前传(三)
- [work] about technical architecture
- Thread knowledge summary
- 视觉系统设计实例(halcon-winform)-10.PLC通讯
猜你喜欢

Redis

什么是Tor?Tor浏览器更新有什么用?

Kubernetes 节点磁盘故障排查

Shell programming specifications and variables

大家最想要的,最全的C语言知识点总结,还不赶紧学习

Getting started with DirectX

Import the virtual machine officially made by Kali Linux into Oracle VirtualBox

LeetCode 面试题 17.21. 直方图的水量 双指针,单调栈/hard

@Bean 与 @Component 用在同一个类上,会发生什么?

【STM32】EXTI
随机推荐
lc marathon 7.26
股票买卖4
Finally, someone finished all the dynamic planning, linked list, binary tree and string required for the interview
Skywalking distributed system application performance monitoring tool - medium
【医疗行业】DICOM converter Tools
How to deploy open source Siyuan privately
网络设备硬核技术内幕 路由器篇 15 从鹿由器到路由器 (下)
Shell programming specifications and variables
Thread knowledge summary
Basic exercises of C language
NEFU117 素数个数的位数【素数定理】
SkyWalking分布式系统应用程序性能监控工具-中
What if win11 wallpaper turns black? The solution of win11 wallpaper blackening
代码覆盖率统计神器-jacoco工具实战
Hdu4496 d-city [concurrent search]
[Yunxiang book club issue 13] multimedia processing tool ffmpeg tool set
深圳市人力资源和社会保障局关于发放脱贫人口就业有关补贴的通知
Disk troubleshooting of kubernetes node
STM32F103C8T6在Arduino框架下驱动SH1106 1.3“ IIC OLED显示
【WORK】关于技术架构