397 Longest Continuous Increasing Subsequence

原题网址:https://www.lintcode.com/problem/longest-continuous-increasing-subsequence/description

描述

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

time

您在真实的面试中是否遇到过这个题?  

样例

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

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

标签
枚举法
动态规划(DP)
数组
 
思路:两次遍历数组,分别找到上升连续子序列从左向右递增最大长度与从左向右递减最大长度,对比返回长度最大值。
 
AC代码:
class Solution {
public:
    /**
     * @param A: An array of Integer
     * @return: an integer
     */
    int longestIncreasingContinuousSubsequence(vector<int> &A) {
        // write your code here
    int n=A.size();
    if (n==0)
    {
        return 0;
    }
    
    int maxLen1=1,maxLen=1;//初始值的设定,子序列的最短长度是1;
    int i=0;
    for (;i<n;)//从左向右递增最大长度;
    {
        while(i+1<n&&A[i]<A[i+1])
        {
            maxLen1++;
            i++;
        }
        
        if (maxLen1>maxLen)
        {
            maxLen=maxLen1;
        }
        maxLen1=1;
        i++;
    }

    maxLen1=1;
    for (i=0;i<n;)//从左向右递减最大长度;
    {
        while(i+1<n&&A[i]>A[i+1])
        {
            maxLen1++;
            i++;
        }
        
        if (maxLen1>maxLen)
        {
            maxLen=maxLen1;
        }
        maxLen1=1;
        i++;
    }

    return maxLen;
    
    }
};
 代码还可以再优化,在一个循环里同时计算递增与递减长度,将较大值赋值给结果,最后return出去。参考:https://www.cnblogs.com/grandyang/p/5858125.html  简直想要跪地膜拜
 
初始AC代码:该版本代码量太大,引入了数组保存每次遍历到的连续单调子序列长度,最后计算出数组最大值return出去。
class Solution {
public:
    /**
     * @param A: An array of Integer
     * @return: an integer
     */
    int longestIncreasingContinuousSubsequence(vector<int> &A) {
        // write your code here
    int n=A.size();
    if (n==0)
    {
        return 0;
    }
    vector<int> tmp;
    int maxLen1=1,maxLen2=1;//初始值的设定,子序列的最短长度是1;
    int i=0;
    for (;i<n;)
    {
        while(i+1<n&&A[i]<A[i+1])
        {
            maxLen1++;
            i++;
        }
        tmp.push_back(maxLen1);    
        
        maxLen1=1;
        i++;
    }

    for (i=0;i<n;)
    {
        while(i+1<n&&A[i]>A[i+1])
        {
            maxLen2++;
            i++;
        }
        tmp.push_back(maxLen2);
        
        maxLen2=1;
        i++;
    }

    int result=tmp[0];
    for (int j=0;j<(int)tmp.size();j++)
    {
        if (tmp[j]>result)
        {
            result=tmp[j];
        }
    }
    return result;
        
    }
};

 

 
 

猜你喜欢

转载自www.cnblogs.com/Tang-tangt/p/9206127.html