【三次过】Lintcode 397:Longest Continuous Increasing Subsequence

给定一个整数数组(下标从 0 到 n-1, n 表示整个数组的规模),请找出该数组中的最长上升连续子序列。(最长上升连续子序列可以定义为从右到左或从左到右的序列。)

样例

给定 [5, 4, 2, 1, 3], 其最长上升连续子序列(LICS)为 [5, 4, 2, 1], 返回 4.

给定 [5, 1, 2, 3, 4], 其最长上升连续子序列(LICS)为 [1, 2, 3, 4], 返回 4.

解题思路:

    用一个循环,同时寻找递增和递减的数列,使用两个变量res1和res2分别记录最长递增和递减数列的长度,一旦递增递减断开,将对应的计数器重置,而max1与max2是记录最长递增和减序列的长度,防止计数器重置后历史数据消失。

class Solution {
public:
    /**
     * @param A: An array of Integer
     * @return: an integer
     */
    int longestIncreasingContinuousSubsequence(vector<int> &A) 
    {
        // write your code here
        if(A.empty())
            return 0;
        
        int res1 = 1;//记录当前连续递增序列的规模
        int res2 = 1;//记录当前连续递减序列的规模
        int max1 = 1;//记录连续递增序列的最大规模
        int max2 = 1;//记录连续递减序列的最大规模
        
        for(int i=0;i<A.size()-1;i++)
        {
            if(A[i] < A[i+1])
            {
                res1++;
                res2 = 1;
            }
            else if(A[i] > A[i+1])
            {
                res2++;
                res1 = 1;
            }
            
            if(res1 > max1)
                max1 = res1;
            if(res2 > max2)
                max2 = res2;
        }
        
        return (max1>max2)?max1:max2;
    }
};

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/80671090
今日推荐