博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Increasing Triplet Subsequence
阅读量:6238 次
发布时间:2019-06-22

本文共 1672 字,大约阅读时间需要 5 分钟。

Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.Formally the function should:Return true if there exists i, j, k such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.Your algorithm should run in O(n) time complexity and O(1) space complexity.Examples:Given [1, 2, 3, 4, 5],return true.Given [5, 4, 3, 2, 1],return false.

Naive Solution: use DP, Time O(N^2), Space O(N)

  dp[i] represents the length of longest increasing subsequence till i including element i in nums array. dp[i] is initialized to be 1.

  dp[i] = max(dp[i], dp[j]+1), where j is an index before i

1 public class Solution { 2     public boolean increasingTriplet(int[] nums) { 3         int[] dp = new int[nums.length]; 4         for (int i=0; i

Better Solution: keep two values. Once find a number bigger than both, while both values have been updated, return true.

small: is the minimum value ever seen untill now

big: the smallest value that has something before it that is even smaller. That 'something before it that is even smaller' does not have to be the current min value.

Example:

3,2,1,4,0,5

When you see 5, min value is 0, and the smallest second value is 4, which is not after the current min value.

 

1 public class Solution { 2     public boolean increasingTriplet(int[] nums) { 3         int small = Integer.MAX_VALUE, big = Integer.MAX_VALUE; 4         for (int n : nums) { 5             if (n <= small) { 6                 small = n; 7             } 8             else if (n <= big) { 9                 big = n;10             }11             else return true;12         }13         return false;14     }15 }

 

转载地址:http://gjdia.baihongyu.com/

你可能感兴趣的文章
Mongodb删除collection
查看>>
ArcEngine应用程序中无法实现TOC图层多选
查看>>
Java-笔记9-复习
查看>>
python---基本数据结构
查看>>
Windows下JDK,Tomcat,Eclipse安装配置
查看>>
vue的checkbox或多选的select的代码例子
查看>>
es6-Set和Map数据结构
查看>>
使用ffmpeg将录屏文件转换成gif
查看>>
作业七 总结
查看>>
Oracle的静默安装 升级和卸载 参考规范
查看>>
高效存储过程分页
查看>>
电脑用U盘启动
查看>>
Web漏洞扫描
查看>>
使用xtrabackup做数据库的增量备份
查看>>
“程序已停止工作”问题的解决方法,停止解决方法
查看>>
[c++] 幂法求特征向量
查看>>
WEB项目(B/S系统)打包安装(总结篇)
查看>>
Cartographer源码阅读(8):imu_tracker
查看>>
U盘,移动硬盘显示显示需要格式化怎么修复
查看>>
JVM基础和调优(一)
查看>>