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.
Credits:
Special thanks to @DjangoUnchained for
adding this problem and creating all test cases.
Subscribe to see which companies
asked this question
这道题要求一个没有排序的数组中是否有3个数字满足前后递增的关系。最简单的办法是动态规划,设置一个数组dp,dp[i]表示在i位置之前小于或者等于数字nums[i]的数字的个数。我们首先将数组dp的每个元素初始化成1.然后开始遍历数组,对当前的数字nums[i],如果存在nums[j]<nums[i] (j<i),那么更新dp[i]=max(dp[i],dp[j]+1).如果在更新dp[i]之后,dp[i]的值为3了,那么就返回true,否则返回false。
代码如下:
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
vector<int> dp(nums.size(),1);
for(int i=0;i<nums.size();i++){
for(int j=0;j<i;j++){
if(nums[j]<nums[i]){
dp[i]=max(dp[i],dp[j]+1);
if(dp[i]==3){
return true;
}
}
}
}
return false;
}
};
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int min1=INT_MAX;
int min2=INT_MAX;
for(auto a:nums){
if(a<=min1)
min1=a;
else if(a<=min2)
min2=a;
else
return true;
}
return false;
}
};