leetcode 300. Longest Increasing Subsequence

来源:互联网 发布:java人员管理系统 编辑:程序博客网 时间:2024/06/06 07:36

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?


way-1 普通遍历

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


way-2:利用map的排序,key是上升个数,value是nums[i]。但是速度并没有way-1快

class Solution {public:    int lengthOfLIS(vector<int>& nums)     {        if (nums.empty()) return 0;        multimap<int, int> mm;        mm.insert(make_pair(1, nums[0]));        for (int i = 1; i < nums.size(); i++)            {            int k = 1;            for (auto it = mm.rbegin(); it != mm.rend(); it++)            {                if (nums[i] > it->second)                {                    k = it->first + 1;                    break;                }            }            mm.insert(make_pair(k, nums[i]));        }        return mm.rbegin()->first;    }};


阅读全文
0 0
原创粉丝点击