LeetCode 354 Russian Doll Envelopes (LIS变形 推荐)

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]).


题目链接:https://leetcode.com/problems/russian-doll-envelopes/

题目分析:这是一道很有趣的题,是一维LIS的变形,n^2的做法就不说了,和一维LIS类似,只不过比较的时候要同时比高和宽,介绍一下nlogn的做法,在一维LIS中直接对其从小到大排序然后二分找修改点即可,二维的情况下,属性1按从小到大排序,若属性1相等,则对属性2按从大到小排序,这里就是巧妙之处,相当于将其按属性1分成了很多组,因为要求严格上升,故每组只能取一个出来,将属性2按从大到小排序就可以保证这点,不会出现一组里取超过一个的情况,然后我们直接对属性2的值找一遍LIS就是答案。

public class Solution {
    
    class Envelope {
        int w, h;
        public Envelope(int w, int h) {
            this.w = w;
            this.h = h;
        }
    }
    
    public int binarySearch(int h, int len, int[] height) {
        int l = 0, r = len - 1, mid = 0, ans = 0;
        while (l <= r) {
            mid = (l + r) >> 1;
            if (h > height[mid]) {
                l = mid + 1;
            }
            else {
                ans = mid;
                r = mid - 1;
            }
        }
        return ans;
    }
    
    public int maxEnvelopes(int[][] envelopes) {    
        int n = envelopes.length;
        Envelope[] e = new Envelope[n];
        for (int i = 0; i < n; i ++) {
            e[i] = new Envelope(envelopes[i][0], envelopes[i][1]);
        }
        Arrays.sort(e, new Comparator<Envelope>() {
            @Override
            public int compare(Envelope e1, Envelope e2) {
                if(e1.w == e2.w) {
                    if(e1.h < e2.h) {
                        return 1;
                    }
                    else if(e1.h > e2.h) {
                        return -1;
                    }
                    else {
                        return 0;
                    }
                }
                else if(e1.w > e2.w) {
                    return 1;
                }
                else {
                    return -1;
                }
            }
        });
        int height[] = new int[n], len = 0;
        for (int i = 0; i < n; i ++) {
            if(len == 0 || height[len - 1] < e[i].h) {
                height[len ++] = e[i].h;
            }
            else {
                int pos = binarySearch(e[i].h, len, height);
                height[pos] = e[i].h;
            }
        }
        return len;
    }
} 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值