LeetCode 674.Longest Continuous Increasing Subsequence

来源:互联网 发布:将软件添加到磁贴 编辑:程序博客网 时间:2024/04/30 23:48

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


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

原创粉丝点击