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
.
这道题是判断数组中是否有三个递增的数字,题目难度为Medium。
题目限定了时间和空间复杂度,所以排序就不考虑了。这里用num0表示当前最小的数字,num1表示存在两个递增数字的情况下比num0大的最小数字。这样遍历数组,如果数字比num0小则更新num0,如果数字介于num0和num1之间则更新num1,如果数字比num1大则存在三个递增的数字。之所以要更新num1,是因为存在[4, 5, 1, 2, 3]这样的数组,在遍历到‘2’时,需要将num1从5更新为2,这样遍历到‘3’时即可返回true。具体代码:
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int num0 = INT_MAX, num1 = INT_MAX;
for(int num:nums) {
if(num <= num0)
num0 = num;
else if(num <= num1)
num1 = num;
else
return true;
}
return false;
}
};
判断中用num <= num0和num <= num1是为了避免判断[1, 2, 2]这样的序列时返回true。