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 increasingTriplet(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;
}
};