题目描述
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.
题目大意
判断一个数组中是否有三个递增的子序列。
(时间复杂度要求为O(N),空间复杂度为O(1))
示例
E1
E2
解题思路
三个变量分别保存,从左至右得到的第一小,第二小和第三小的数字,并在赋值的过程中判断是否是递增的。
复杂度分析
时间复杂度:O(N)
空间复杂度:O(1)
代码
class Solution { public: bool increasingTriplet(vector<int>& nums) { if(nums.size() == 0) return false; long low = nums[0], med = INT_MAX + 1, high = INT_MAX + 1, count = 1; for(int i = 1; i < nums.size(); ++i) { // 若当前数字比low记录的要小,则更新low数值 if(nums[i] < low) { low = nums[i]; } // 否则依次判断med和high else if(nums[i] > low) { // 若med尚未被赋值,则将其赋值,表示递增数值加一 if(med == INT_MAX + 1) { med = nums[i]; count++; } // 若当前数字比med记录的要小,则更新med的数值 else { if(nums[i] < med) { med = nums[i]; } // 如果当前数值比med记录的要大,代表以有三个递增数列,退出循环 else if(nums[i] > med) { count++; break; } } } } return count == 3; } };