zoukankan      html  css  js  c++  java
  • 300. Longest Increasing Subsequence

    #week12

    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?

    Credits:
    Special thanks to @pbrother for adding this problem and creating all test cases.

    分析:

    最长不下降子序列

    状态转换:

    if (nums[j] < nums[i] && (f[j] + 1 > f[i])) 
    f[i] = f[j] + 1;

    题解:

     1 class Solution {
     2 public:
     3     int lengthOfLIS(vector<int>& nums) {
     4         int size = nums.size();
     5         if (size == 0) return 0;
     6         int f[size], max = 1;
     7         f[0] = 1;
     8         for (int i = 1; i < size; i++) {
     9             f[i] = 1;
    10             for (int j = 0; j < i; j++) {
    11                 if (nums[j] < nums[i] && (f[j] + 1 > f[i])) {
    12                     f[i] = f[j] + 1;   
    13                     if (f[i] > max) max = f[i];
    14                 }
    15             }
    16         }
    17         return max;
    18     }
    19 };

    其他人题解,O(nlogn)

     1 class Solution {
     2 public:
     3 int lengthOfLIS(vector<int>& nums) {
     4     vector<int> res;
     5     for(int i=0; i<nums.size(); i++) {
     6         auto it = std::lower_bound(res.begin(), res.end(), nums[i]);
     7         if(it==res.end()) res.push_back(nums[i]);
     8         else *it = nums[i];
     9     }
    10     return res.size();
    11 }
    12 };
  • 相关阅读:
    线程池的优雅关闭实践
    InheritableThreadLocal原理解析
    线程池踩坑
    两个线程通讯(生产-卖面包问题)
    谈谈redis的热key问题如何解决
    中国软件杯选题A1数据智能分析报告系统
    《程序员的思维修炼》读后感
    《算法导论》读后感
    《重构》读后感
    《代码整洁之道》读后感
  • 原文地址:https://www.cnblogs.com/iamxiaoyubei/p/8278270.html
Copyright © 2011-2022 走看看