当前位置:网站首页>leetcode:334. 递增的三元子序列
leetcode:334. 递增的三元子序列
2022-08-10 10:09:00 【OceanStar的学习笔记】
题目来源
题目描述
题目解析
本质是问最长递增子序列长度能否超过2而已
一次遍历
因为我们需要求解的长度仅仅为3,所以我们可以直接将这个三元子序列的值记录下来;
使用两个指针m1和m2,初始化为INT_MAX,然后遍历数组:
- 如果m1 >= curr,则令m1 = curr
- 如果m1 < curr && m2 >= curr,则令m2 = curr
一旦m2被更新了,说明一定会有一个数小于m2,也就是我们成功组成了一个长度为2的递增子序列。所以我们一旦遍历到比m2还大的数,我们直接返回ture。
如果我们遇到比m1小的数,还是要更新m1,有可能的话也要更新m2为更小的值,毕竟m2的值越小,能组成长度为3的递增序列的可能性越大
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int m1 = INT32_MAX, m2 =INT32_MAX;
for(auto a : nums){
if(m1 >= a){
m1 = a;
}else if(m2 >= a){
m2 = a;
}else{
return true;
}
}
return false;
}
};
暴力超时
class Solution {
bool process(vector<int>& nums, int idx, std::vector<int>&path){
if(idx == nums.size()){
return path.size() >= 3;
}
bool p1 = process(nums, idx + 1, path);
bool p2 = false;
if(path.empty() || path.back() < nums[idx] ){
path.emplace_back(nums[idx]);
p2 = process(nums, idx + 1, path);
path.pop_back();
}
return p1 || p2;
}
public:
bool increasingTriplet(vector<int>& nums) {
std::vector<int>path;
return process(nums, 0, path);
}
};
类似题目
边栏推荐
- "Scalability" extensibility best practices: lessons from eBay
- The Generation of Matlab Symbolic Functions and the Calculation of Its Function Values
- 数据库的约束
- LeetCode Algorithm 1403. 非递增顺序的最小子序列
- VBA: Inputbox Function and Inputbox Method
- VBA: 遍历文件抓取指定条件的数据
- Thrift -- 跨语言RPC 框架
- CSDN 21 Days Learning Challenge - Polymorphism (05)
- String interception function in SQL
- 2022.8.7-----leetcode.636
猜你喜欢
干货!ASSANet:让PointNet++更快更强
【微服务架构】微服务与SOA架构(2)
SQL中的字符串截取函数
因子分析(SPSS)
Dalian University of Technology & Pengcheng & UAE propose a mixed-scale triple network ZoomNet for camouflaged target detection, with SOTA performance!
ESP8266 Tutorial 2 - Burn AT Firmware
[Concept of Theory of Knowledge] "Progress in the Theory of Reason" University of Leuven 2022 latest 220-page doctoral dissertation
[C language] Floating point number rounding
Taro小程序跨端开发入门实战
[Azure Cloud] What is the difference between a service endpoint and a private link?point of view (1)
随机推荐
LCD模块如何建立联系分析
ESP8266 Tutorial 1 - Introduction to ESP8266 Hardware Platform
Flutter实战-请求封装(五)之Isolate线程改造
ZZULIOJ 1124: Merge two sorted arrays
「业务架构」TOGAF建模:业务功能分解图
「敏捷建模」纪律:敏捷设计理念
解决ASP.NET Core在Task中使用IServiceProvider的问题
网络安全笔记6——数字证书与公钥基础设施
细说Redis监控和告警
「时序数据库」使用cassandra进行时间序列数据扫描
ZZULIOJ 1116 Delete elements [delete]
【微服务架构】微服务与SOA架构(2)
[Internet of Things Architecture] The most suitable open source database for the Internet of Things
「数据战略」结果驱动的企业数据策略:组织和治理
网络安全笔记5——数字签名
在兄弟连战狼班参加PHP培训做行业领先人才
91.(cesium之家)cesium火箭发射模拟
dedecms支持Word内容一键上传
lua初学
干货!ASSANet:让PointNet++更快更强