[LeetCode] 674. Longest Continuous Increasing Subsequence 最長連續遞增序列


 

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.

 

這道題讓我們求一個數組的最長連續遞增序列,由於有了連續這個條件,跟之前那道 Number of Longest Increasing Subsequence 比起來,其實難度就降低了很多。可以使用一個計數器,如果遇到大的數字,計數器自增1;如果是一個小的數字,則計數器重置為1。用一個變量 cur 來表示前一個數字,初始化為整型最大值,當前遍歷到的數字 num 就和 cur 比較就行了,每次用 cnt 來更新結果 res,參見代碼如下:

 

解法一:

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

 

下面這種方法的思路和上面的解法一樣,每次都和前面一個數字來比較,注意處理無法取到錢一個數字的情況,參見代碼如下:

 

解法二:

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

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/674

 

類似題目:

Number of Longest Increasing Subsequence

Minimum Window Subsequence

 

參考資料:

https://leetcode.com/problems/longest-continuous-increasing-subsequence/

https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/107352/Java-code-6-liner

https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/107365/JavaC%2B%2BClean-solution

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM