最长非降低子序列(O(nlogn))(offer收割)

题目

  如题算法

思路

  核心思想是,维护一个数组ends,它记录了长度为k的子序列的末尾元素的最小值。听起来很抽象,咱们不妨手动演示一遍整个过程。数组

  假设数组a={2,9,4,27,29,15,7},令length表示当前找到的最长非降低子序列的长度。初始时length=1,ends[1]=2。spa

  i=1,length=2,ends[2]=9;code

  i=2,length=2,ends[2]=4,缘由是4比9更容易和后面的数构成非降低子序列;it

  i=3,length=3,ends[3]=27;io

  i=4,length=4,ends[4]=29;function

  i=5,length=4,15能和ends[2]=4链接起来,而且它比ends[3]=27更容易和后面的数构成非降低子序列,所以ends[3]=15;class

  i=6,length=4,end[3]=7。static

  能够看到,整个算法就是找到ends中第一个大于当前数的位置。假设当前数为a[i],找到的位置为t,说明ends[t-1]<=a[i],那么a[i]能够和ends[t-1]链接起来,构成长度为i的子序列,同时ends[t]>a[i],说明a[i]要比ends[t]更容易和后面的数构成子序列,所以进行替换。能够说,算法的思想是贪心加二分。word

代码

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;
                else
                    high=mid;
            }
            if(ends[low]>array[i])
                ends[low]=array[i];
            else{
                length++;
                ends[length]=array[i];
            }
        }
        System.out.println(length);
    }
}
复制代码
相关文章
相关标签/搜索