算法分析與設計課程作業第二十週#1

算法分析與設計課程作業第二十週#1

期末考也結束了,爲了湊個整數,寫多一篇複習時看的題吧。算法這門課感覺自己考得還算滿意,而人工智能就慘不忍睹了。
這道是複習時看的一道題。

300. Longest Increasing Subsequence

Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that 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?

思路

可以用貪心算法的思路,遍歷序列,每次從序列中看當前那個數能否放到找到的臨時序列中,即如果找到的數大於所有找到的臨時序列的數,就置其於末尾,找到的序列長度加一,如果不是就用它換掉第一個大於它的數(爲了爲開始確定更長的子序列(可能以被換掉的數承接)提供可能)。注意最後的臨時序列並不是最長子序列,但其長度與最長子序列相等。
使用二分查找可使得每次查找複雜度爲O(log2n),總體時間複雜度爲O(nlog2n)。
順帶一提,

代碼

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
    vector<int> res;
    for(int i=0; i<nums.size(); i++) {
        vector<int>::iterator it = lower_bound(res.begin(), res.end(), nums[i]);
        if(it==res.end()) res.push_back(nums[i]);
        else *it = nums[i];
    }
    return res.size();
}
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章