1、最长连续子序列的长度
Given an unsorted array of integers, find the length of longest
continuous
increasing subsequence (subarray).
Example 1:
Input: [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3.
Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4.
Example 2:
Input: [2,2,2,2,2] Output: 1 Explanation: The longest continuous increasing subsequence is [2], its length is 1.
Note: Length of the array will not exceed 10,000.
这是LeetCode的第674道题,解法如下:
class Solution {
public:
int findLengthOfLCIS(vector<int>& nums) {
int maxLen = 1;
int cnt = 1;
int i = 0;
if(nums.size() <= 0)
{
return 0;
}
for(int i=0; i<nums.size()-1; i++)
{
if(nums[i] < nums[i+1])
{
cnt++;
}
else
{
cnt=1;
}
maxLen = max(maxLen, cnt);
}
return maxLen;
}
};
2、最长递增子序列的长度
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?
//找到最长递增子序列
int arr[] = {5,3,4,6,8,7,11,38,24};
int num = sizeof(arr)/sizeof(arr[0]);
vector<int> v(arr, arr+num-1);
//思路:动态规划的方法
//以arr[i]结尾的序列最长长度为dp[i]
//dp[0]=1
//dp[1]=1
//dp[2]=dp[1]+1=2
//dp[3]=max(dp[2]+1, dp[1]+1, dp[0]+1)=max(3,2,2)=3
//总结dp[i]的计算方法:和前面的数逐个相比,如果>=a[j], max = max(dp[j+1], max); 如果小于所有a[j] max=1
// 初始化:max=1
// 如果a[i]>=a[j]:max = max(dp[j]+1, max)
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> dp(nums.size(), 1);
int maxLen = 0;
for(int i=0; i<nums.size(); i++)
{
int temp = 1;
for(int j=0; j<i; j++)
{
if(nums[i] > nums[j])
{
temp = max(temp, dp[j]+1);
}
}
dp[i] = temp;
maxLen = max(maxLen, dp[i]);
}
return maxLen;
}
};