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

题目

  如题

思路

  核心思想是,维护一个数组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;
                else
                    high=mid;
            }
            if(ends[low]>array[i])
                ends[low]=array[i];
            else{
                length++;
                ends[length]=array[i];
            }
        }
        System.out.println(length);
    }
}
复制代码

转载于:https://juejin.im/post/5c39b1d26fb9a049a81f8ced

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值