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

334. Increasing Triplet Subsequence

2016-03-03 08:57 381 查看
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
.

本题也就是一个最长递增子串的问题延伸,求解思路就是不能追求某个值,而是应该利用起数组下标的优势遍历数组,找的是大小关系,而不是某个特定的结果,否则就容易陷入误区。

而关于最长递增子串问题具体可以看joylnwang大神的分析
http://blog.csdn.net/joylnwang/article/details/6766317
public class Solution {

public boolean increasingTriplet(int[] nums) {

int x = nums.length;

if(x < 3) return false;

int a = Integer.MAX_VALUE;

int b = Integer.MAX_VALUE;

for(int i : nums)

{

if(a >= i)a = i;

else if( b >= i) b = i ;

else return true;

}

return false;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: