[LeetCode]674. Longest Continuous Increasing Subsequence 解题报告(C++)

[LeetCode]674. Longest Continuous Increasing Subsequence 解题报告(C++)

题目描述

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.

题目大意

  • 给定一个未排序的数组,返回最长的连续递增小序列长度.

解题思路

方法1:

  • 遍历数组,
  • 需要作记录. 前一个数据与记录长度.
  • 若当前数大于前一个数,cnt++;若不满足.cnt置为1.
  • 最后通过比较更新最长的长度为多少.

代码实现:

class Solution {
public:
    int findLengthOfLCIS(vector<int>& nums) {
        int res = 0, cnt = 0, cur = INT_MAX;
        for (auto num : nums) {
            if (num > cur) {
                cnt++;
            }
            else {
                cnt = 1;
            }
            res = max(res, cnt);
            cur = num;
        }
        return res;
    }
};

小结

  • 计数 根据情况不同做重置与自增.
  • 记录前面的值 需要向明白记录哪些值. 怎么用.
  • 用 min/max 做更新 很好用!

猜你喜欢

转载自blog.csdn.net/qjh5606/article/details/81411404