您的位置:首页 > 产品设计 > UI/UE

LeetCode 334 Increasing Triplet Subsequence

2016-07-03 18:06 489 查看
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
.
参考:大海里的太阳

维护两个数的递增序列,如果能找到第三个数比前两个大,则返回true。

设置一个small,一个big,small<big。如果能找到一个大于small和big的就返回true。时间复杂度为O(n)。

public boolean increasingTriplet(int[] nums) {
int small = Integer.MAX_VALUE, big = Integer.MAX_VALUE;
for (int value : nums) {
if (value <= small) small = value;
else if (value <= big) big = value;
else return true;
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: