第八周:[Leetcode]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(n^2)时间复杂度。

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        if(nums.size() == 0)
        return 0;
    int lis[nums.size()],ans = 0;
    for(int i = 0;i<nums.size();i++){
        lis[i] = 1;
        for(int j = 0;j < i;j++){
            if(nums[j] < nums[i])
                lis[i] = lis[j] + 1 > lis[i] ? lis[j] + 1 : lis[i];
        }
        ans = lis[i] > ans ? lis[i] : ans;
    }
    return ans;
}
};

第二种方法:使用二分查找不断更新对应路径值中最小的结束节点,也是按照老师上课讲的方法,O(nlogn)时间复杂度

class Solution {
public:
    int binary_search(vector<int> a,int target){
    int l = 0,r = a.size() - 1,mid;
    while(r - l > 1){
        mid = l + ((r - l)>>1);
        if(target > a[mid])
            l = mid;
        else if(target == a[mid])
            return mid;
        else
            r = mid;
    }
    return l;
}

int lengthOfLIS(vector<int>& nums) {
    if(nums.size() == 0)
        return 0;
    vector<int> a;
    a.push_back(nums[0]);
    for(int i = 1;i<nums.size();i++){
        if(nums[i] > a[a.size() - 1])
            a.push_back(nums[i]);
        else if(nums[i] < a[a.size() - 1]){
            int index = binary_search(a, nums[i]);
            if(index == 0 && nums[i] < a[0])
                a[0] = nums[i];
            else if(index < a.size() - 1 && a[index] != nums[i])
                a[++index] = nums[i] < a[index] ? nums[i] : a[index];
        }
    }
    return a.size();
}
};
点赞