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

Increasing Triplet Subsequence

2016-02-22 20:48 525 查看
334.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 
[1, 2, 3, 4, 5]
,

return 
true
.

Given 
[5, 4, 3, 2, 1]
,

return 
false
.

class Solution {
public:
bool increasingTr
a0d1
iplet(vector<int>& nums) {
int first = INT_MAX;
int second = INT_MAX;                                              //通过两个变量记录序列的前两个值
for (size_t i=0;i+1<nums.size();++i)
{
if (nums[i]<nums[i+1]&&first>nums[i]&&second>nums[i+1])    //当first与second均比当前值和随后值大时更新
{
first = nums[i];
second = nums[i+1];
}
if (nums[i]>second||nums[i+1]>second)                      //若当前值或随后值比second大则形成递增序列
{
return true;
}
if (nums[i]>first&&nums[i]<second)                         //若当前值处于first和second中间,更新second
{
second = nums[i];
}
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: