Increasing Triplet Subsequence(三个递增数字子序列)
【难度:Medium】
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.
给定一乱序数组,判断其内部是否存在三个顺序递增的数字子序列,
如存在0<= i < j < k <= n-1,使得a[i]
解题思路
设置两个变量fisrt,second来记录已出现的两个递增的数字,遍历数组,且维护first<second
的关系,那么当出现一个数字大于second时,则存在符合条件的递增子序列,返回true,否则返回false。
c++代码如下:
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
if (nums.size() < 3)
return false;
int first = INT_MAX;
int second = INT_MAX;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] <= first) {
first = nums[i];
} else if (nums[i] <= second) {
second = nums[i];
} else {
return true;
}
}
return false;
}
};