1,题目要求
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
给定未排序的数组返回是否在数组中存在增加的长度为3的子序列。
正式的功能应该:
如果存在i,j,k则返回true
这样arr [i] <arr [j] <arr [k]给定0≤i<j <k≤n-1否则返回false。
注意:您的算法应该以O(n)时间复杂度和O(1)空间复杂度运行。
2,题目思路
对于这道题,要求判断一个数组中是否存在长度为3的子序列。
一开始在做的时候,以为这个子序列是连续的,觉得非常简单。但是后来发现并不是这样,而是需要找到一个子序列,未必是连续的。
因此,在问题的解决上,我们可以设置两个参数,分别用来记录到当前元素为止的最小值和第二小的值,如果当前的值比这两个值都大,自然是找到了这样的三序列了。
3,代码实现
static auto speedup = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
if(nums.size() <3)
return false;
int minSoFar = INT_MAX;
int _2ndMinSoFar = INT_MAX;
for(auto x:nums){
if(x <= minSoFar)
minSoFar = x;
else if(x <= _2ndMinSoFar)
_2ndMinSoFar = x;
else
return true;
}
return false;
}
};