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
.
用min,max记录递增序列中的第一个和第二个数,若出现a[i]大于这两者就返回true,更新两个值!
class Solution { public: bool increasingTriplet(vector<int>& a) { const int n=a.size(); if(n<3) return false; int min=INT_MAX,max=INT_MAX; for(int i=0;i<n;i++) { if(a[i]<=min) min=a[i]; else if(a[i]<=max) max=a[i]; else return true; } return false; } };
算法思想二:
用L1,L2标记当前找到1个还是2个递增序列,min1,min2记录当前自增序列中最小值和第二小值。
<span style="font-size:18px;">class Solution { public: bool increasingTriplet(vector<int>& a) { const int n=a.size(); if(n<3) return false; int l1=1,l2=0; int Min1=std::min(a[0],a[1]),Min2; if(a[0]<a[1]) l2=1,Min2=a[1]; for(int i=2;i<n;i++) { if(l2&&Min2<a[i]) { return true; } if(l1&&a[i]>Min1) { if(l2==0) Min2=a[i],l2=1; else if(a[i]<Min2) Min2=a[i]; } if(a[i]<Min1) Min1=a[i]; } return false; } };</span>