Question
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.
Solution
数学逻辑。
Code
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int c1 = INT_MAX, c2 = INT_MAX;
for (int i : nums) {
if (i <= c1) // 当前最小的数
c1 = i;
else if (i <= c2) // 第二或者第三大的数
c2 = i;
else // 如果存在一个比当前最小的大,且比第二大的数大(能够成为第二大,说明它之前有比它小的),那么这个数前面肯定有两个比它小的
return true;
}
return false;
}
};