当前位置:网站首页>【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)
边栏推荐
- 人脸合成效果媲美StyleGAN,而它是个自编码器
- 浅谈防勒索病毒方案之主机加固
- 别再问我如何制作甘特图了!
- mysql根据多字段分组——group by带两个或多个参数
- pycharm专业版使用
- 如何监控海外服务器性能
- npm出现报错 npm WARN config global `--global`, `--local` are deprecated. Use `--location=global
- 【MySQL】ERROR 2002 (HY000): Can‘t connect to local MySQL server through socket ‘/tmp/mysql.sock‘
- MySQL八股文背诵版
- MLX90640 infrared thermal imaging temperature measuring sensor module development notes (9)
猜你喜欢
随机推荐
Sentinel 2A data preprocessing and calculation of six common vegetation indices in snap software
别再问我如何制作甘特图了!
ISME | 沈其荣团队韦中组-土壤生物障碍发生的根际微生物组诊断
IJCAI 2022 outstanding papers published, China won two draft in 298 the first author
C language game ------ greedy snake ---- for Xiaobai
学习的时候碰见的一个sql问题,希望大佬们可以解答一二?
何享健“A拆A”又败一局,美的旗下美智光电终止创业板IPO
TiCDC synchronization delay problem
传奇服务端GOM引擎和GEE引擎区别在哪里?
用支持LaTex的Markdown语句编辑一个数学公式
BGP简单实验
Mysql各个大版本之间的区别
bean的生命周期
Create and copy conda environment
Nacos分级存储模型-集群配置与NacosRule负载均衡
[Numpy] np.select
【C语言】扫雷游戏实现(初阶)
苹果手机用久了卡顿,学会这样清理缓存,清理后和新机一样流畅
The interviewer was stunned by the self-growth of 4 mainstream database IDs in one breath
如何监控海外服务器性能









