最长上升连续子序列 LintCode
问题:
给定一个整数数组(下标从 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.
给定 [1, 1, 1, 1, 1], 其最长上升连续子序列(LICS)为 [1], 返回 1.
Java 代码,时间复杂度为O(n):
1 public class Solution { 2 /** 3 * @param A an array of Integer 4 * @return an integer 5 */ 6 public static int longestIncreasingContinuousSubsequence(int[] A) { 7 if(A.length==0) //如果为空这返回0 8 return 0; 9 int hz,hj,r,maxz,maxj; //依次为增序搜索头指针,降序搜索头指针,尾指针,增序搜索最大值,降序搜索最大值。 10 hz=hj=0; 11 r=maxz=maxj=1; 12 13 while(r<A.length){ 14 if(A[r]<A[r-1]){ 15 maxz = Math.max(maxz, r-hz); 16 hz = r; 17 }else if(A[r]>A[r-1]){ 18 maxj = Math.max(maxj, r-hj); 19 hj = r; 20 }else{ 21 hz = hj = r; 22 } 23 r++; 24 } 25 maxz = Math.max(maxz, r-hz); 26 maxj = Math.max(maxj, r-hj); 27 return Math.max(maxz, maxj); 28 } 29 }
浙公网安备 33010602011771号