LeetCode 334. Increasing Triplet Subsequence(长度为3的递增子序列)
2016-04-29 14:37
501 查看
原题网址:https://leetcode.com/problems/increasing-triplet-subsequence/
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
方法:保存3个候选值,其中第1、2个位递增的一对,第3个位比第1个还小的数字。
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.
方法:保存3个候选值,其中第1、2个位递增的一对,第3个位比第1个还小的数字。
public class Solution { public boolean increasingTriplet(int[] nums) { int count = 0; int[] buf = new int[3]; for(int i=1; i<nums.length; i++) { if (count == 0 && nums[i-1] < nums[i]) { buf[0] = nums[i-1]; buf[1] = nums[i]; count = 2; } else if (count == 2) { if (buf[1] < nums[i]) return true; if (buf[0] < nums[i]) { buf[1] = nums[i]; } else if (buf[0] > nums[i]) { buf[2] = nums[i]; count = 3; } } else if (count == 3) { if (buf[1] < nums[i]) return true; if (buf[2] >= nums[i]) { buf[2] = nums[i]; } else { buf[0] = buf[2]; buf[1] = nums[i]; count = 2; } } } return false; } }
相关文章推荐
- 判断一个值是不是DBNull.Value
- 【WEB前端】太原web前端讲师兼UI设计师css选择器知识讲解
- Maven中-DskipTests和-Dmaven.test.skip=true的区别
- FMDB-FMDatabaseQueue
- IOS键盘的相关设置(UITextfield)
- Hibernate中的Query一些基本用法
- gnueabi相关的两个交叉编译器: gnueabi和gnueabihf 区别
- DataGrid中的请求携带参数
- MySQL 通用查询日志(General Query Log)
- UIButton常用属性和函数详解
- String Stringbuffer Stringbuilder 的区别
- [SoapUI] Mock Service
- IOS上 关于状态栏的相关设置(UIStatusBar)
- 使用UI-Router设置页面标题
- easyui onSortColumn:alertColumn
- leetcode——96——Unique Binary Search Trees
- 百度编辑器UEditor常用设置函数大全
- ios UITableViewCell 左滑删除时,改变删除按钮背景颜色
- UIView常用属性和函数
- easyui-window title的赋值和获取