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
.
bool increasingTriplet(vector<int>& nums) {
int i,n1,n2;
int n=nums.size();
if(n<3) return false;
for( i=0;i<n;i++)
{
if(i>0&&nums[i]>nums[i-1])
{
n1=nums[i-1];
n2=nums[i];
break;
}
}
if(i==n) return false;
int poss=INT_MAX;
for(i=i+1;i<n;i++)
{
if(nums[i]>n2) return true;
else
if(nums[i]>n1&&nums[i]<n2) n2=nums[i];
else
if(nums[i]>poss&&nums[i]<=n1)
{
n1=poss;
n2=nums[i];
}
if(nums[i]<n1) poss=nums[i];
}
return false;
}
思路二:
转载于此链接
bool increasingTriplet(vector<int>& nums) {
int small=INT_MAX, big=INT_MAX;//初始时,设置small和big为三个数中的前两个,一旦遇到比这两个都大的,返回true
for(auto num:nums)
{
if(num<=small) small=num;//首先,如果遇到的数<=small,更新
else if(num<=big) big=num;//比small大,而<=big,更新big
else return true;//找到了第三个数
}
return false;
}
举个例子,{1,2,-10,3},当遍历到0是,small=0,big=2,虽然相对顺序不对,但一旦3>2,它肯定大于1,这是仍是对。如果遇到大于-10,但<2的数时,可以更新big,此时,big和small的坐标顺序是满足要求的。
看来我刚开始想多了,没想清楚。