您的位置:首页 > 产品设计 > UI/UE

[leetcode 300] Longest Increasing Subsequence

2016-03-29 23:13 316 查看
Question:

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(n2)
的情况:

就是在判断pre后面的第一个元素如果大于前面的元素,而且后面的第二个元素大于pre且小于pre后面的第一个元素,则判断子串是从pre后的第二个元素开始递增的。否则为pre后的第一个元素递增。

代码如下:

class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if(nums.empty())
return 0;
int maxlen = 1;
for(int i = 0; i < nums.size()-1; ++i){
int pre = nums[i];
int count = 1;
for(int j = i+1; j < nums.size(); ++j){
if(nums[j] > pre){
if(j < nums.size()-1 && nums[j+1] > pre && nums[j] > nums[j+1]){
j++;

}
pre = nums[j];
++count;
}
}
if(count > maxlen){
maxlen = count;
}
}
return maxlen;
}
};


复杂度为O(n
log n) 的情况:参考

举例解释:

For example, if
nums = [5,6,7,1,2,8,3,4,0,5,9]


then after we prcoess the 7:
S = [5,6,7]


after w process the 2:
S = [1,2,7]


after we process the 8:
S = [1,2,7,8]


Then we process the 3:
S = [1,2,3,8]


We process the 4:
S = [1,2,3,4]


and now the next three lements:
S = [0,2,3,4,5,9]


S is not the actual subsequence, but it is the right length (end ends in the right number).
虽然最终不是实际的子串,但是长度是正确的,如果在原地该,空间复杂度为1;
代码如下:

class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if(nums.empty())
return 0;
int maxlen = 1;

vector<int>::iterator m = nums.begin();  // m will mark the virtual "S.end()".
for (int& val : nums) {
auto it = lower_bound(nums.begin(), m, val);
*it = val;
if (it == m)
m++;
}

return m - nums.begin();
}
};


关于c++的lower_bound()详看C++类型文章。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: