LeetCode刷題Medium篇Increasing Triplet Subsequence
阿新 • • 發佈:2019-01-03
題目
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;
}
}