397、 最长上升连续子序列

 

给定一个整数数组(下标从 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.

挑战

使用 O(n) 时间和 O(1) 额外空间来解决

思路:本文感觉是利用了类似于指针的方法

从头到尾遍历

public static int longestIncreasingContinuousSubsequence(int[] A)
    {
        int inc =1;
        int desc = 1;
        int longest =1;
        if(A.length==0)
        {
            return 0;//需要注意的是这里一定要做出判断为空,否则当数组为空时会报错
        }
        for(int i=1;i<A.length;i++)
        {
            if(A[i]>A[i-1])
            {
                inc++;
                desc =1;
            }
            else if(A[i]<A[i-1])
            {
                desc++;
                inc=1;
            }
            else
            {
                inc=1;
                desc =1;
            }
            longest = Math.max(longest, Math.max(inc,desc));
        }
        return longest;
    }

猜你喜欢

转载自blog.csdn.net/Sml_banzhuiyixi/article/details/82855718
今日推荐