ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[LeetCode] 354. Russian Doll Envelopes

2021-03-05 13:01:45  阅读:231  来源: 互联网

标签:信封 int envelope 354 envelopes Russian size LeetCode left


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 is greater than the width and height of the other envelope.

Return the maximum number of envelopes can you 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:

  • 1 <= envelopes.length <= 5000
  • envelopes[i].length == 2
  • 1 <= wi, hi <= 104

俄罗斯套娃信封问题。

给你一个二维整数数组 envelopes ,其中 envelopes[i] = [wi, hi] ,表示第 i 个信封的宽度和高度。

当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。

请计算 最多能有多少个 信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。

注意:不允许旋转信封。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/russian-doll-envelopes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题类似300题,我直接给出最优解,DP + 二分法。300题是在一个一维数组里找最长的上升子序列。这道题是在一个二维数组<width, height>里寻找一个最长上升子序列,首先需要对input数组排序,先对宽度 w 进行升序排序,如果遇到 w 相同的情况,则按照高度 h 降序排序。之后把所有的 h 作为一个数组,在这个数组上计算 LIS 的长度就是答案。我这里直接粘贴一个大神的截图作参考

 

 然后在 h 上寻找最长递增子序列

 

时间O(nlogn)

空间O(n)

Java实现

 1 class Solution {
 2     public int maxEnvelopes(int[][] envelopes) {
 3         // corner case
 4         if (envelopes.length < 2) {
 5             return envelopes.length;
 6         }
 7 
 8         // normal case
 9         // <w, h>
10         Arrays.sort(envelopes, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);
11         int[] dp = new int[envelopes.length];
12         int size = 0;
13         for (int[] e : envelopes) {
14             int left = 0;
15             int right = size;
16             while (left < right) {
17                 int mid = left + (right - left) / 2;
18                 if (dp[mid] < e[1]) {
19                     left = mid + 1;
20                 } else {
21                     right = mid;
22                 }
23             }
24 
25             dp[left] = e[1];
26             if (left == size) {
27                 size++;
28             }
29         }
30         return size;
31     }
32 }

 

LIS类相关题目

LeetCode 题目总结

标签:信封,int,envelope,354,envelopes,Russian,size,LeetCode,left
来源: https://www.cnblogs.com/cnoodle/p/14485551.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有