Longest Increasing Subsequence

来源:互联网 发布:不破坏数据做活动分区 编辑:程序博客网 时间:2024/05/14 11:09

DP: O(n^2)

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


看到的别人的解法,O(nlgn)

lower_bound返回迭代器解引用作为左值,很巧妙

class Solution {public:    int lengthOfLIS(vector<int>& nums) {vector<int> res;        for (int i = 0; i < nums.size(); i++)  {            if (res.empty() || nums[i] > res.back()) res.push_back(nums[i]);            else *lower_bound(res.begin(), res.end(), nums[i]) = nums[i];        }        return res.size();    }};

0 0