当前位置:网站首页>【LeetCode】Day105-递增的三元子序列
【LeetCode】Day105-递增的三元子序列
2022-07-29 12:55:00 【倒过来是圈圈】
题目
题解
双向遍历
维护数组 nums 中的每个元素左边的最小值和右边的最大值,只要出现leftMin[i] < nums[i] < rightMax[i],即返回true
class Solution {
public boolean increasingTriplet(int[] nums) {
int n=nums.length;
if(n<3)
return false;
int[] leftMin=new int[n];
leftMin[0]=nums[0];
for(int i=1;i<n;i++){
leftMin[i]=Math.min(leftMin[i-1],nums[i]);
}
int[] rightMax=new int[n];
rightMax[n-1]=nums[n-1];
for(int i=n-2;i>=0;i--){
rightMax[i]=Math.max(rightMax[i+1],nums[i]);
}
//遍历中间值nums[i]
for(int i=1;i<n-1;i++){
if(nums[i]>leftMin[i]&&nums[i]<rightMax[i])
return true;
}
return false;
}
}
时间复杂度: O ( n ) O(n) O(n),遍历数组三次
空间复杂度: O ( n ) O(n) O(n),三个数组
贪心
使用贪心策略将空间复杂度降到O(1),其核心思想为:为了找到递增的三元子序列,三元组第一个元素 first 和 第二个元素 second 应该尽可能地小,此时找到递增的三元子序列的可能性更大。
具体算法如下:赋初始值,first=nums[0],second=+∞,已经满足second > first了,现在找第三个数third
(1) 如果third比second大,那就是找到了,直接返回true
(2) 如果third比second小,但是比first大,那就把second的值设为third,然后继续遍历找third
(3) 如果third比first还小,那就把first的值设为third,然后继续遍历找third
class Solution {
public boolean increasingTriplet(int[] nums) {
int n=nums.length;
if(n<3)
return false;
int first=nums[0],second=Integer.MAX_VALUE;
for(int i=1;i<n;i++){
int third=nums[i];
if(third>second)//1<2<3
return true;
else if(third>first)//1<3<2
second=third;
else//3<1<2
first=third;
}
return false;
}
}
时间复杂度: O ( n ) O(n) O(n),遍历数组一次
空间复杂度: O ( 1 ) O(1) O(1)
边栏推荐
猜你喜欢
随机推荐
html+css+php+mysql实现注册+登录+修改密码(附完整代码)
HCIP第十三天笔记(BGP的路由过滤、BGP的社团属性、MPLS)
[Numpy] np.select
Hash table implementation code
浅谈防勒索病毒方案之主机加固
Container is changed | deploy MySQL cluster in the Rancher
常坐飞机的你,为什么老惦记着“升舱”?
「 工业缺陷检测深度学习方法」最新2022研究综述
bean的生命周期
Chapter 6 c + + primer notes 】 【 function
别再问我如何制作甘特图了!
Py之eli5:eli5库的简介、安装、使用方法之详细攻略
mariadbackup物理备份使用——筑梦之路
[MySQL view] View concept, create, view, delete and modify
Navicat如何连接MySQL
MySQL 安装报错的解决方法
Go - reading (7), CopySheet Excelize API source code (the from and to the int)
conda环境创建及复制
MySQL database installation (detailed)
MySQL基础(DDL、DML、DQL)








