LeetCode题—数组tag:674. 最长连续递增序列

给定一个未经排序的整数数组,找到最长且连续的的递增序列,并返回该序列的长度。

示例 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值