LeetCode 674. Longest Continuous Increasing Subsequence

来源:互联网 发布:centos 移除文件夹 编辑:程序博客网 时间:2024/04/30 23:53

题目:
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.

Note: Length of the array will not exceed 10,000.

思路: 遍历整个数组 ,找连续最长的就行,分段找各个连续的最大值,注意如果都是连续递增的,那要加一个count和max的比较。

代码:

class Solution {public:    int findLengthOfLCIS(vector<int>& nums) {        int len = nums.size();        if (len < 2){//如果nums的长度小于2,直接返回nums的长度            return len;        }        int max = 1;//最终的最大值         int count = 1;//计数        for (int i = 1; i < len;++i){            if (nums[i] > nums[i - 1]){//从第2个元素开始遍历,如果这个数比前一个大,count加1                ++count;            }            else{//否则将此时的count值赋给max,count 重置为1                max = max > count ? max : count;                count = 1;            }        }        max = max > count ? max : count;//如果一直是增长的,那第此时还需要比较count和max的值,选最大的赋给max        return max;    }};

结果: 16ms

阅读全文
0 0
原创粉丝点击