【LeetCode 300】 Longest Increasing Subsequence Medium

題目描述

Given an unsorted array of integers, find the length of longest increasing subsequence.

Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4 
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 

Note:

There may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.

Follow up: Could you improve it to O(n log n) time complexity?

思路

思路一:

動態規劃,記錄每個位置以當前位置結尾的最長LIS長度,O(n^2)

思路二:
二分,對於每個數字,查找dp數組中第一個不小於它的數字,如果不存在,dp數組末尾加上這個數字,否則替換位置。

代碼

代碼一:

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        if (nums.empty()) return 0;
        int n = nums.size();
        vector<int> dp(n, 1);
        
        int res = 1;
        for (int i=1; i<n; ++i) {
            for (int j=i-1; j>=0; --j) {
                if (nums[i] > nums[j]) dp[i] = max(dp[i], dp[j]+1);
            }
            res = max(dp[i], res);
        }
        
        return res; 
    }
};

代碼二:

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        if (nums.empty()) return 0;
        int n = nums.size();
        
        vector<int> dp;
        for (int num : nums) {
            int left = 0, right = dp.size()-1;
            while(left <= right) {
                int mid = left + (right - left) / 2;
                if (dp[mid] < num) left = mid + 1;
                else right = mid - 1;
            }
            if (left >= 0 && left < dp.size() && dp[left] >= num) dp[left] = num;
            else dp.push_back(num);
        }
        
        return dp.size();
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章