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.
Example 1:
Input: [1,2,3,4,5] Output: true
Example 2:
Input: [5,4,3,2,1] Output: false
解题思路:
该题是经典的问题最长不降子序列问题的变形。
要找一个长度为三的递增子序列,于是创建一个包含三个元素的数组,表示这三个数分别是多少,初始化为0xfffffff。从左到右遍历整个数组,每次遍历,更改这三个元素:如果新加入的值小于dp[k]并且大于dp[k-1],则更新dp[k],退出此次循环。
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
vector<int>dp(3,0xfffffff);
for(int i=0; i<nums.size(); ++i){
for(int j=0; j<3; ++j){
if(nums[i] > dp[j]) continue;
else {dp[j] = nums[i]; break;}
}
}
return dp[2] != 0xfffffff;
}
};