博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Longest Increasing Subsequence
阅读量:7284 次
发布时间:2019-06-30

本文共 2094 字,大约阅读时间需要 6 分钟。

A typical O(n^2) solution uses dynamic programming. Let's use lens[j] to denote the length of the LIS ending with nums[j]. The state equations are

lens[0] = 1

lens[j] = max_{i = 0, 1, 2, ..., j - 1}(lens[j], lens[i] + 1)

Then the length of the LIS of nums is just the maximum value in lens. The code is as follows.

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

The O(nlogn) solution is much more complicated. Try to read through the explanation of it in first. The code is as follows.

class Solution {public:    int lengthOfLIS(vector
& nums) { if (nums.empty()) return 0; vector
ends{nums[0]}; for (int num : nums) { if (num < ends[0]) ends[0] = num; else if (num > ends.back()) ends.push_back(num); else { int l = 0, r = ends.size() - 1; while (l < r) { int m = l + (r - l) / 2; if (ends[m] < num) l = m + 1; else r = m; } ends[r] = num; } } return ends.size(); }};

If you look at the else part carefully, you may notice that it can be done using lower_bound. So we will have a much shorter code, like .

1 class Solution { 2 public: 3     int lengthOfLIS(vector
& nums) { 4 vector
ends; 5 for (int num : nums) { 6 auto it = lower_bound(ends.begin(), ends.end(), num); 7 if (it == ends.end()) ends.push_back(num); 8 else *it = num; 9 }10 return ends.size();11 }12 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4934562.html

你可能感兴趣的文章
协程(Coroutine)并不是真正的多线程(转)
查看>>
java 中 ResourceBundle 使用 国际化使用
查看>>
使用Git Bash for Windows
查看>>
【087】Stylish & Greasemonkey
查看>>
uva 10626 - Buying Coke(记忆化搜索)
查看>>
WIN8.1 PRO RTM VOL.Enterprise.2013.10.17
查看>>
arcengine 要素渲染和专题图制作
查看>>
安装VS2005的sp1补丁错误,未通过数字签名检查(轉)
查看>>
XP里查看进程详细信息的命令
查看>>
PHP函数详细剖析之rtrim函数 By ACReaper
查看>>
如何禁止页面滚动
查看>>
Docker 安装
查看>>
Struts1 MVC框架的工作原理
查看>>
xdebug调试一直等待连接
查看>>
写个线程池
查看>>
android面试题之四
查看>>
NET 开发者必备的工具箱
查看>>
程序员爬《邪不压正》影评,发现细丝极恐的细节,电影就要这样看
查看>>
这大概是全世界最酷的“工牌”!拿到的中国人个个都不简单
查看>>
当京东小哥坐在电影院的前排,抬头看到了这样的一幕
查看>>