题目描述:
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.
Note: Your algorithm should run in O(n) time complexity and O(1) space complexity.
题意:
在一个无序数组里找出一个严格递增的三元组。
思路:
标记最小和次小,遇见比它俩都大的就成功了。。。开始写了一堆if。。。哭辽。
代码:
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int n = nums.size();
int num1 = INT_MAX;
int num2 = INT_MAX;
for (int i=0; i<n; ++i) {
if (nums[i] <= num1) {
num1 = nums[i];
}
else if (nums[i] <= num2) {
num2 = nums[i];
}
else {
return true;
}
}
return false;
}
};