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

来源:互联网 发布:淘宝卖阿迪达斯的c店 编辑:程序博客网 时间:2024/05/29 10:20

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 is3 ([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
原创粉丝点击