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)
Note:
Rotation is not allowed.
Example:
Input: [[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]).
class Solution { public int maxEnvelopes(int[][] envelopes) { if(envelopes == null || envelopes.length == 0 || envelopes[0] == null || envelopes[0].length != 2) return 0; Arrays.sort(envelopes, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); int dp[] = new int[envelopes.length]; int len = 0; for(int[] envelope : envelopes){ int index = Arrays.binarySearch(dp, 0, len, envelope[1]); if(index < 0) index = -(index + 1); dp[index] = envelope[1]; if(index == len) len++; } return len; } }
对width从小到大排序,height从大到小排序,防止有width tie,例如【4,3】,【4,4】的话就会把【4,4】也算进去,所以应该排成【4,4】,【4,3】
总结:如果width从小到大排列的话,我们只需要找到longest increasing sequence of height, 所以先对width排序,然后对height逆排序,然后就对height找LIS即可
private int binarySearchPosition(int[] dp,int target,int hi){ int low = 0; while(low <= hi){ int mid = low + (hi - low)/2; if(target == dp[mid]) return mid; else if(target < dp[mid]) hi = mid - 1; else if(target > dp[mid]) low = mid + 1; } return low; }
还可以不用库函数里的binarySearch, 需要先Arrays.fill(dp, Integer.MAX_VALUE)
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步