题目
如题
思路
核心思想是,维护一个数组ends,它记录了长度为k的子序列的末尾元素的最小值。听起来很抽象,我们不妨手动演示一遍整个过程。
假设数组a={2,9,4,27,29,15,7},令length表示当前找到的最长非下降子序列的长度。初始时length=1,ends[1]=2。
i=1,length=2,ends[2]=9;
i=2,length=2,ends[2]=4,原因是4比9更容易和后面的数构成非下降子序列;
i=3,length=3,ends[3]=27;
i=4,length=4,ends[4]=29;
i=5,length=4,15能和ends[2]=4连接起来,并且它比ends[3]=27更容易和后面的数构成非下降子序列,因此ends[3]=15;
i=6,length=4,end[3]=7。
可以看到,整个算法就是找到ends中第一个大于当前数的位置。假设当前数为a[i],找到的位置为t,说明ends[t-1]<=a[i],那么a[i]可以和ends[t-1]连接起来,构成长度为i的子序列,同时ends[t]>a[i],说明a[i]要比ends[t]更容易和后面的数构成子序列,因此进行替换。可以说,算法的思想是贪心加二分。
代码
package com.iqiyi;public class Test {public static void main(String[] args){int[] array=new int[]{2,9,4,27,29,15,7};int[] ends=new int[array.length+1];ends[1]=array[0];int length=1;for(int i=1;i<array.length;i++){int low=1;int high=length;while(low<high){int mid=(low+high)/2;if(ends[mid]<=array[i])low=mid+1;elsehigh=mid;}if(ends[low]>array[i])ends[low]=array[i];else{length++;ends[length]=array[i];}}System.out.println(length);}
}
复制代码