LeetCode 674.Longest Continuous Increasing Subsequence

本文介绍了解决LeetCode 674题目的方法,通过一次遍历找到最长连续递增子序列的长度,并提供了一个简单易懂的C++实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode 674.Longest Continuous Increasing Subsequence

Description:

Given an unsorted array of integers, find the length of longest continuous increasing subsequence.

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.

分析:

这道题其实就是动态规划找最长递增子序列的简易版,只要求找最长连续递增子串,可以减少一层循环,时间复杂度为O(n).

例子:
来看看例子[1,3,5,4,7],首先我们用vector来定义一个length,表示子串的长度,先置为1,然后循环遍历这个vector容器,比较前后两个数的大小,更新每个length的大小。最后再取出length的最大值,即为结果。
首先长度置为1:length[0]=length[1]=length[2]=length[3]=length[4]=1
根据上述算法得到:
当nums[0]=1时, length[0]=1
当nums[1]=3时, 3>1, length[1]=2
当nums[2]=5时, 5>3, length[2]=3
当nums[3]=4时, 4<5, length[3]=1
当nums[4]=7时, 7>4, length[4]=2

代码如下:

#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
    int findLengthOfLCIS(vector<int>& nums) {
        vector<int> length(nums.size());
        for (int i = 0; i < nums.size(); i++) {
            length[i] = 1;
        }
        for (int i = 1; i < nums.size(); i++) {
            if (nums[i] > nums[i - 1]) {
                length[i] = length[i - 1] + 1;
            }
        }
        // 找出最大的length
        int max = 0;
        for (int i = 0; i < nums.size(); i++) {
            // cout << length[i] << " ";
            if (length[i] > max) max = length[i];
        }
        return max;
    }
};
int main() {
    Solution s;
    int n;
    cin >> n;
    vector<int> nums(n);
    for (int i = 0; i < n; i++) {
        cin >> nums[i];
    }
    cout << s.findLengthOfLCIS(nums) << endl;
    return 0;
}

运行结果如下:
输入:
5
1 3 5 4 7
输出:
1 2 3 1 2
3


可以参考我的另一篇文章最长递增子序列——动态规划

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值