[LeetCode] Russian Doll Envelopes

来源:互联网 发布:origin如何导出数据 编辑:程序博客网 时间:2024/05/16 09:02

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

o(n**2) 的动态规划就不写了,写一种结合BinarySearch和dp结合的o(nlogn)的算法:

public class Solution { public int maxEnvelopes(int[][] envelopes) { if(envelopes.length==0) return 0; Arrays.sort(envelopes,new Comparator<int[]>() {@Overridepublic int compare(int[] o1, int[] o2) {return o1[0]-o2[0]==0?o2[1]-o1[1]:o1[0]-o2[0];//这里这样的排序方式特别重要,只有这样排序才能保证后面的BinarySearch是有意义的                                              //如:[1,1],[1,2],[1,3];} }); int[] dp=new int[envelopes.length]; int len=0; for(int i=0;i<envelopes.length;i++){ int pos=Arrays.binarySearch(dp,0,len,envelopes[i][1]); if(pos<0) pos=-(pos+1); dp[pos]=envelopes[i][1]; if(pos==len) len++; } return len; }}

 

原创粉丝点击