给定一个未经排序的整数数组,找到最长且连续的的递增序列,并返回该序列的长度。
示例 1:
输入: [1,3,5,4,7]
输出: 3
解释: 最长连续递增序列是 [1,3,5], 长度为3。
尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为5和7在原数组里被4隔开。
示例 2:输入: [2,2,2,2,2]
输出: 1
解释: 最长连续递增序列是 [2], 长度为1。注意:数组长度不会超过10000。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-continuous-increasing-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
提交:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int findLengthOfLCIS(vector<int>& nums) {
int n = 1;
int max = 1;
int len = nums.size();
if (len == 0)
{
return 0;
}
for (int i = 0; i < len-1; i++)
{
if (nums[i + 1] > nums[i])
{
n++;
if (n > max)
{
max = n;
}
}
if (nums[i + 1] <= nums[i])
{
if (n != 1)
{
if (n > max)
{
max = n;
}
n = 1;
}
}
}
return max;
}
int main()
{
int num;
vector<int> nums;
while (cin >> num)
{
nums.push_back(num);
if (cin.get() == '\n')
{
break;
}
}
int c;
c = findLengthOfLCIS(nums);
cout << c << endl;
return 0;
}
};
方法不够好,以后再优化
在自己的编译器上(带注释):
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int findLengthOfLCIS(vector<int>& nums)
{
int n = 1; //每个递增段的长度计数
int max = 1;
int len = nums.size();
if (len == 0)
{
return 0; //如果没有输入,就返回0,结束函数。这个不能少,因为n初始是1
}
for (int i = 0; i < len-1; i++) //因为for循环里用了i+1,所以循环到<len-1,不然到最后一个的时候会超
{
if (nums[i + 1] > nums[i]) //说明进入递增段
{
n++;
if (n > max)
{
max = n;
}
}
if (nums[i + 1] <= nums[i]) //非递增
{
if (n != 1)
{
if (n > max)
{
max = n;
}
n = 1;
}
}
}
return max;
}
int main()
{
int num;
vector<int> nums;
while (cin >> num)
{
nums.push_back(num);
if (cin.get() == '\n')
{
break;
}
}
int c;
c = findLengthOfLCIS(nums);
cout << c << endl;
return 0;
}