一. 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.
Difficulty:Medium
TIME:15MIN
解法
看到这个题的一瞬间,就觉得这道题怎么和求最长递增子序列Longest Increasing Subsequence那么像,细想一下觉得解法应该也差不多,用的就是求最长递增子序列的解法二,代码也差不多就那样写了:
bool increasingTriplet(vector<int>& nums) {
if(nums.size() < 3)
return false;
vector<int> v{nums[0]};
for(size_t i = 1; i < nums.size(); i++) {
if(nums[i] > v.back() && v.size() < 3) {
v.push_back(nums[i]);
if(v.size() == 3)
return true;
continue;
}
for(size_t j = 0; j < v.size(); j++) {
if(nums[i] <= v[j]) {
v[j] = nums[i];
break;
}
}
}
return false;
}
代码的时间复杂度为 O(n) 。
总结
如果要输出所有长度为3的序列就不能这样做了,当然可以采用暴力搜索的方式求解,具体可以查看Increasing Subsequences。