LeetCode 674. Longest Continuous Increasing Subsequence最长连续递增序列 (C++/Java)

题目:

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.

分析:

给定一个未经排序的整数数组,找到最长且连续的的递增序列。

注意是要找到连续的递增序列,由于需要连续,这道题就变得简单了许多。我们可以创建一个和给定数组同样大小的数组res,用来记录到当前元素递增序列的长度。

nums 1 3 5 4 7
res 1 2 3 1 2

初始化res[0]为1,因为有一个数的话,大小也是1。如果当前元素大于前一个元素,则长度加1,否则,意味着当前元素无法和前面的序列继续构成递增这一条件,我们要计算后面的递增序列的大小,所以重新置为1。遍历完数组后,直接返回res中最大值即可。

当然我们也可以不适用数组来存储,可以发现比较数组元素是否递增时,如果保持递增,序列长度加1,那么我们可以创建两个变量,一个用来保存当前的递增序列长度,如果下一个元素符合条件,就加1,否则就重新置为1,另一个变量用来保存最终解,每一次更新当前递增序列长度,都和最终解比较大小,将大的值赋给最终解。

nums 1 3 5 4 7
temp 1 2 3 1 2
res 1 2 3 3 3

程序:

C++

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

Java

class Solution {
    public int findLengthOfLCIS(int[] nums) {
        if(nums.length == 0) return 0;
        int res = 1;
        int maxTemp = 1;
        for(int i = 1; i < nums.length; ++i){
            if(nums[i-1] < nums[i])
                ++maxTemp;
            else
                maxTemp = 1;
            res = Math.max(res, maxTemp);
        }
        return res;
    }
}

你可能感兴趣的:(LeetCode 674. Longest Continuous Increasing Subsequence最长连续递增序列 (C++/Java))