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

LeetCode *** 300. Longest Increasing Subsequence

2016-04-13 22:21 441 查看
题目:

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?

分析:

我目前做的是n^2时间复杂度。有时间了想n*logn复杂度的做法吧。占坑。

代码:

class Solution {
public:
int lengthOfLIS(vector<int>& nums) {

int max=0,size=nums.size();

for(int i=0;i<size;++i){
int tmp=1,pre=nums[i],next=nums[i];

for(int j=i-1;j>=0;--j){
if(nums[j]<pre){
tmp++;
pre=nums[j];
}
}
for(int j=i+1;j<size;++j){
if(nums[j]>next){
tmp++;
next=nums[j];
}
}
max=max>tmp?max:tmp;

}
return max;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: