Leetcode 354. Russian Doll Envelopes

问题描述

You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.

What is the maximum number of envelopes can you Russian doll? (put one inside other)

Example:
Given envelopes = [[5,4],[6,4],[6,7],[2,3]], the maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

问题分析:
如果信封是一维的数据,则只需将数据进行排序,找到最长递增序列即可,同理对于二维数据,首先进行排序,先按宽度进行递增排序,宽度相同按照高度递增排序,然后dp[i]=max(dp[i],dp[j]+1),if envelopes[i][0]>envelopes[j][0]&& envelopes[i][1]>envelopes[j][1]。时间复杂度是n2。由于已经排好序,可以使用二分查找进行优化。维护一个高度递增的序列,其表示有效信封的高度,计算当前信封是否可以被套进某一层,即。为了避免相同宽度的信封被重复计算,在排序时相同宽度按照高度递减排序,这样只要当前宽度的某个信封可以套在外部,那么同一宽度的之后的信封必然不会被计算。代码如下:

    public int maxEnvelopes(int[][] envelopes) {
        if(envelopes==null||envelopes.length==0)
            return 0;
        int n=envelopes.length;
        Arrays.sort(envelopes,new Comparator<int[]>(){
            public int compare(int[]a,int[]b){
                if(a[0]!=b[0])
                    return a[0]-b[0];
                else
                    return b[1]-a[1];}
            });
        ArrayList<Integer> list=new ArrayList<Integer>();
        for(int i=0;i<n;i++){
            if(list.size()==0||list.get(list.size()-1)<envelopes[i][1])
                list.add(envelopes[i][1]);
            int l=0;
            int r=list.size()-1;
            while(l<r){
                int m=l+(r-l)/2;
                if(list.get(m)<envelopes[i][1])
                    l=m+1;
                else
                    r=m;
            }
            list.set(r,envelopes[i][1]);//相同宽度,取能够套在外面的高度较小的那个信封
        }
        return list.size();
    }

参考链接:http://bookshadow.com/weblog/2016/06/07/leetcode-russian-doll-envelopes/

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值