题目
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
十分钟尝试
做过一个类似的题目,利用动态规划尝试,记得我当时做的时候失误了,第一反应是下面的完美代码,其实有个重要的错误点!!!
看断点行,i-1有两个增加序列,现在i大于i-1,不能直接加1就是i的自增序列长度,因为i大于i-1,不一定大于i-1自增序列里面的其他数字,比如
2 1 5 0 3
数组 1 1 2 2 3(这个3是错误的,不是连续自增,大于i-1就不一定大于其他的元素,如果是连续自增自序列,没有问题)
所以dp[i]的值 应该是:
寻找i前面所有元素中,比i小的元素中找dp[i]值最大的count加1.
修改后代码如下:
class Solution {
public boolean increasingTriplet(int[] nums) {
if(nums.length<3) return false;
int[] dp=new int[nums.length+1];
dp[0]=1;
for(int i=1;i<nums.length;i++){
int count=0;
for(int j=0;j<i;j++){
if(nums[i]>nums[j]){
count=Math.max(count,dp[j]);
}
}
dp[i]=count+1;
if(dp[i]==3){
return true;
}
}
return false;
}
}
代码正确,但是题目要求O(1)的空间,我的显然不是,是O(n)
优化解法
仔细体会一下,我感觉这个思路不是通用的。仅仅是因为题目要求3个,并且判断是否存在。
class Solution {
public boolean increasingTriplet(int[] nums) {
int small=Integer.MAX_VALUE;
int big=Integer.MAX_VALUE;
for(int i=0;i<nums.length;i++){
int curr=nums[i];
if(curr<=small){
small=curr;
}
else if(curr<=big){
big=curr;
}
else{
return true;
}
}
return false;
}
}