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.
要找固定长度的递增子序列,我们可以用两个元素存放满足关系的i,j的值,对于之后来的新元素如果大于arr[j]返回true,如果小于arr[i]更新i,如果在arr[i],arr[j]之间就更新j,遍历整个数组就行了,代码如下:
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
if(!nums.size()) return false;
int length=nums.size();
int min=0,se_min=-1;
for(int i=1;i<length;i++){
if(se_min==-1){
if(nums[i]>nums[min])
se_min=i;
if(nums[i]<nums[min])
min=i;
}else if(nums[i]>nums[se_min]){
return true;
}else if(nums[i]<=nums[min]){
min=i;
}else if(nums[i]<nums[se_min]){
se_min=i;
}
}
return false;
}
};

本文介绍了一种在未排序数组中寻找长度为3的递增子序列的方法,该算法的时间复杂度为O(n),空间复杂度为O(1)。通过维护两个变量来跟踪可能的递增序列起点,可以高效地解决问题。
470

被折叠的 条评论
为什么被折叠?



