Middle-题目44:334. Increasing Triplet Subsequence
2016-05-31 16:05
477 查看
题目原文:
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.
题目大意:
给出一个数组,判断是否存在一个递增的长度为3的子序列。
题目分析:
(1) 朴素解法:O(n3)暴力搜索;
(2) 最长递增子列:引用Middle-题目33的方法判断最长递增子列的长度是否>=3,最好的时间复杂度是O(nlogn)。
(3) O(n)算法:扫描一遍数组,令a1是当前最小值,a2是a1以后次小值,则如果当前的数比a2还大,就存在。
源码:(language:java)
成绩:
1ms,beats 34.32%,众数1ms,65.68%
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.
题目大意:
给出一个数组,判断是否存在一个递增的长度为3的子序列。
题目分析:
(1) 朴素解法:O(n3)暴力搜索;
(2) 最长递增子列:引用Middle-题目33的方法判断最长递增子列的长度是否>=3,最好的时间复杂度是O(nlogn)。
(3) O(n)算法:扫描一遍数组,令a1是当前最小值,a2是a1以后次小值,则如果当前的数比a2还大,就存在。
源码:(language:java)
public class Solution { public boolean increasingTriplet(int[] nums) { int a1 = Integer.MAX_VALUE,a2 = Integer.MAX_VALUE; for(int num : nums) { if(num<=a1) a1=num; else if(num<=a2) a2=num; else return true; } return false; } }
成绩:
1ms,beats 34.32%,众数1ms,65.68%
相关文章推荐
- 线程加载数据后的ui线程刷新实现
- HBuilder工作空间修改
- Java LinkedBlockingQueue 分析
- Property List Programming Guide(一)
- Middle-题目33:300. Longest Increasing Subsequence
- 利用spt_values求2个时间段内所有的日期。主要用于关联数据。
- LXC quick start
- UE4 蓝图里添加Cpp文件,不在VS解决方案里显示的问题
- Middle-题目21:62. Unique Paths
- UITextFielddelegate委托方法注释
- java中String、StringBuffer和StringBuilder区别
- SSH+Easyui之TreeGrid树形展现数据 - 推酷
- java序列化和serialVersionUID
- Middle-题目12:96. Unique Binary Search Trees
- mybatis框架中validationQuery选项的作用
- Maven工程build时几个Warning的处理
- 给UILabel 或者 UIButton标题加下划线
- 从客户端(XXX)中检测到有潜在危险的Request.Form 值
- UI手势
- 设计模式--Builder