美文网首页
674. Longest Continuous Increasi

674. Longest Continuous Increasi

作者: xingzai | 来源:发表于2019-07-07 23:21 被阅读0次

    题目链接
    tag:
    -Easy;

    • Sliding Window;

    question
      Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).

    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.

    思路:
      比较简单,滑动窗口,只要一个辅助变量当作窗口左边界,如果当前一个元素 num[i] 比 num[i-1] 大说明窗口增加,否者重新开始窗口。代码如下:

    class Solution {
    public:
        int findLengthOfLCIS(vector<int>& nums) {
            // 滑动窗口
            if (nums.empty())
                return 0;
            if (nums.size() == 1)
                return 1;
            int res = 1, left = -1;
            for (int i=1; i<nums.size(); ++i) {
                if (nums[i] > nums[i-1])
                    res = max(res, i-left);
                else
                    left = i - 1;
            }
            return res;
        }
    };
    

    相关文章

      网友评论

          本文标题:674. Longest Continuous Increasi

          本文链接:https://www.haomeiwen.com/subject/plrwhctx.html