LeetCode 之 Increasing Triplet Subsequence
2016-04-12 11:23
483 查看
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
return
Given
return
要找固定长度的递增子序列,我们可以用两个元素存放满足关系的i,j的值,对于之后来的新元素如果大于arr[j]返回true,如果小于arr[i]更新i,如果在arr[i],arr[j]之间就更新j,遍历整个数组就行了,代码如下:
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.
要找固定长度的递增子序列,我们可以用两个元素存放满足关系的i,j的值,对于之后来的新元素如果大于arr[j]返回true,如果小于arr[i]更新i,如果在arr[i],arr[j]之间就更新j,遍历整个数组就行了,代码如下:
class Solution { public: bool increasingTriplet(vector<int>& nums) { if(!nums.size()) return false; int length=nums.size(); int min=0,se_min=-1; for(int i=1;i<length;i++){ if(se_min==-1){ if(nums[i]>nums[min]) se_min=i; if(nums[i]<nums[min]) min=i; }else if(nums[i]>nums[se_min]){ return true; }else if(nums[i]<=nums[min]){ min=i; }else if(nums[i]<nums[se_min]){ se_min=i; } } return false; } };
相关文章推荐
- libjpeg.so.62: no version information available (required
- 遍历jenkins build后的文件夹,找出最新“build NO.”复制到制定目录进行操作
- 第五章 consul key/value
- dequeueReusableCellWithIdentifier: 与dequeueReusableCellWithIdentifier: forIndexPath:的区别
- iPhone键盘自定义及通知
- sqlite 中的query操作
- android AsyncQueryHandler详解
- Tui-x 基础使用
- 有block回调的UIButton和Alert
- Unique Paths
- iOS _UIButton 高亮变灰 效果去掉方法
- iOS 打包上传 Version 和 Build 的意义
- 总是弹出“Building workspace has encountered a problem. Errors during build.”的窗口
- 移动UI设计-表单设计
- 移动UI设计-主要导航模式
- NGUI在5.3打包失败问题
- NGUI在5.3打包失败问题
- unable to dequeue a cell with identifier Identify - must register a nib or a class for the identifie
- 真机测试时报 You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated li
- com.mysql.jdbc.PacketTooBigException: Packet for query is too large (1157 > 1024).