Givenan unsorted array return whether an increasing subsequence of length 3 existsor not in the array.
Formallythe 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.
Youralgorithm should run in O(n) time complexity and O(1) spacecomplexity.
Examples:
Given [1, 2, 3, 4,5],
return true.
Given [5, 4, 3, 2,1],
return false.
Credits:
Special thanks to @DjangoUnchained foradding this problem and creating all test cases.
这题要求在线性的时间内使用常数空间求出某个数组是否有连续的长度大于等于3的递增子串,
设数组为b1,b2,…bn,设定两个数a,b,遍历数组,当a为空的时候,a=bi,当a不为空的时候,当bi>a的时候而b为空的时候b=bi,b不为空的时候如果bi>b,则说明已经发现了递增子串,返回true,如果b<=bi,假如之后有一个数bk和a,b,构成了三连递增子串,那么,a,bi,bk也必定构成三连递增子串,所以只需要检查a,bi和之后的数是否构成递归子串就好了,这里b=bi,
当a不为空bi<=a的时候,假如a,bk,bp构成了三连递增子串,那么bi,bk,bp也一定构成三连递增子串,只需检查bi和之后的数是否构成递增子串就好了,这里a=bi
以后记得当输入数据为int的时候,可以把min初始化为INT_MAX,或者把max初始化为-INT_MIN
class Solution {
public:
boolincreasingTriplet(vector<int>& nums) {
int a = 0, b = 0; int aNull=true,bNull=true;
for (auto u : nums)
{
if (aNull)
{
aNull = false;
a = u;
}
else
{
if (u > a)
{
if (bNull)
{
b = u; bNull=false;
}
else
{
if (u > b)
{
return true;
}
else
{
b = u;
}
}
}
else
{
a = u;
}
}
}
return false;
}
};
简单版本:
class Solution {
public:
boolincreasingTriplet(vector<int>& nums) {
int a = INT_MAX, b = INT_MAX;
for (auto u : nums)
{
if (u <= a) a = u;
else
{
if (u <= b) b = u;
else
{
return true;
}
}
}
return false;
}
};