其他分享
首页 > 其他分享> > LeetCode 354. Russian Doll Envelopes

LeetCode 354. Russian Doll Envelopes

作者:互联网

原题链接在这里:https://leetcode.com/problems/russian-doll-envelopes/

题目:

You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.

One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.

Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).

Note: You cannot rotate an envelope.

Example 1:

Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

Example 2:

Input: envelopes = [[1,1],[1,1],[1,1]]
Output: 1

Constraints:

题解:

Sort the envelopes based on width ascending first, if widths are equal, based on height decending order.

Now width is sorted, we need to find the longest increasing heights.

Note: If widths are equal, need to sort height in decending order. 

e.g. [5, 8], [5, 9] if we don't sort height in decending order, 8 and 9 would be both counted and result is 2. However, width is not increasing, result should be 1.

Time Complexity: O(nlogn). n = envelopes.length.

Space: O(n).

AC Java:

 1 class Solution {
 2     public int maxEnvelopes(int[][] envelopes) {
 3         if(envelopes == null || envelopes.length == 0){
 4             return 0;
 5         }
 6         
 7         Arrays.sort(envelopes, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);
 8         int n = envelopes.length;
 9         int[] minLast = new int[n];
10         minLast[0] = envelopes[0][1];
11         int len = 1;
12         for(int i = 1; i < n; i++){
13             int index = Arrays.binarySearch(minLast, 0, len, envelopes[i][1]);
14             if(index < 0){
15                 index = -(index + 1);
16             }
17             
18             minLast[index] = envelopes[i][1];
19             if(index + 1 > len){
20                 len = index + 1;
21             }
22         }
23   
24         return len;
25     }
26 }

类似Longest Increasing Subsequence.

标签:index,int,len,height,width,354,envelopes,Russian,LeetCode
来源: https://www.cnblogs.com/Dylan-Java-NYC/p/16396704.html