当前位置:网站首页>LeetCode_单调栈_中等_456.132 模式
LeetCode_单调栈_中等_456.132 模式
2022-08-09 11:20:00 【小城老街】
1.题目
给你一个整数数组 nums ,数组中共有 n 个整数。132 模式的子序列由三个整数 nums[i]、nums[j] 和 nums[k] 组成,并同时满足:i < j < k 和 nums[i] < nums[k] < nums[j] 。
如果 nums 中存在 132 模式的子序列 ,返回 true ;否则,返回 false 。
示例 1:
输入:nums = [1,2,3,4]
输出:false
解释:序列中不存在 132 模式的子序列。
示例 2:
输入:nums = [3,1,4,2]
输出:true
解释:序列中有 1 个 132 模式的子序列: [1, 4, 2] 。
示例 3:
输入:nums = [-1,3,2,0]
输出:true
解释:序列中有 3 个 132 模式的的子序列:[-1, 3, 2]、[-1, 3, 0] 和 [-1, 2, 0] 。
提示:
n == nums.length
1 <= n <= 2 * 105
-109 <= nums[i] <= 109
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/132-pattern
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.思路
(1)暴力穷举法
该方法比较容易想到,即穷举所有的子序列 [nums[i], nums[j], nums[k]] (i < j < k),如果存在满足 nums[i] < nums[k] < nums[j] 的子序列,则直接返回 true。如果穷举结束之后仍未找到,则说明数组 nums 中不存在 132 模式的子序列,返回 false 即可。需要注意的是,该方法的时间复杂度较高,为 O(n3),在 LeetCode 上提交会出现“超出时间限制”的提示!
(2)单调栈
思路参考该 LeetCode 用户题解。
3.代码实现(Java)
//思路1————暴力穷举法
class Solution {
public boolean find132pattern(int[] nums) {
for (int i = 0; i < nums.length - 2; i++) {
for (int j = i + 1; j < nums.length - 1; j++) {
if (nums[i] >= nums[j]) {
continue;
}
for (int k = j + 1; k < nums.length; k++) {
if (nums[i] < nums[k] && nums[k] < nums[j]) {
return true;
}
}
}
}
return false;
}
}
//思路2————单调栈
class Solution {
public boolean find132pattern(int[] nums) {
Stack<Integer> stack = new Stack<>();
int nums_k = Integer.MIN_VALUE;
//从后往前遍历
for (int i = nums.length - 1; i >= 0; i--) {
//由于 nums_k
if (nums[i] < nums_k) {
return true;
}
//维护单调递减栈(栈顶元素最小,栈底元素最大)
while (!stack.isEmpty() && stack.peek() < nums[i]) {
nums_k = Math.max(nums_k, stack.pop());
}
stack.push(nums[i]);
}
return false;
}
}
边栏推荐
猜你喜欢
【VIBE: Video Inference for Human Body Pose and Shape Estimation】论文阅读
matlab simulink的scope 示波器光标如何移动记录
激光条纹中心提取——灰度重心法
【Robustness of VQA-1】——2019-EMNLP-Don’t Take the Easy Way Out
[Essence] Analysis of the special case of C language structure: structure pointer / basic data type pointer, pointing to other structures
wait system call
wpf path xaml写法和c#写法对比
Qt获取EXE可执行文件的上一级目录下的文件
Number theory knowledge
PTA 实验7-5 输出大写英文字母(10 分)
随机推荐
End-to-End Object Detection with Fully Convolutional Network学习笔记
Win10调整磁盘存储空间详解
Number theory knowledge
Antdv+Asp.net WebApi开发学生信息管理系统(一)
wait系统调用
Cesium加载三维模型数据
未来装备探索:数字孪生装备
PAT1001
OC-块对象
mysql + redis + flask + flask-sqlalchemy + flask-session 配置及项目打包移植部署
Oracle Database Architecture
PAT1014 未解决
抗积分饱和 PID代码实现,matlab仿真实现
How tall is the B+ tree of the MySQL index?
使用gdb调试多进程程序、同时调试父进程和子进程
父类的main方法可以被继承么?有什么特殊?
PTA 实验7-5 输出大写英文字母(10 分)
x86 Exception Handling and Interrupt Mechanism (1) Overview of the source and handling of interrupts
湖南进芯电子替代TIC2000的可能性
电磁场与电磁波-场论基础