zoukankan      html  css  js  c++  java
  • 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)

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

     1 public class Solution {
     2     public int maxEnvelopes(int[][] envelopes) {
     3         if(envelopes==null||envelopes.length==0||envelopes[0]==null||envelopes[0].length!=2) return 0;
     4         Arrays.sort(envelopes,new Comparator<int[]>(){
     5             public int compare(int[] i1,int[] i2){
     6                 if(i1[0]==i2[0]) return i2[1]-i1[1];
     7                 else return i1[0]-i2[0];
     8             }
     9         });
    10         int[] dp = new int[envelopes.length];
    11         int len = 0;
    12         for(int[] envelope:envelopes){
    13             int end =binarysearch(dp,0,len,envelope[1]);
    14             if(end==len) len++;
    15         }
    16         return len;
    17     }
    18     public int binarysearch(int[] dp,int left,int right,int target){
    19         while(left<right){
    20             int mid = left+(right-left)/2;
    21             if(dp[mid]>=target) right = mid;
    22             else left = mid+1;
    23         }
    24         dp[left] = target;
    25         return left;
    26     }
    27 }
    28 //the time complexity could be nlogn, the space complexity could be O(n);
  • 相关阅读:
    常见三种字符编码的区别:ASCII、Unicode、UTF-8
    字节、字、bit、byte的关系
    SQLite 3 中的数据类型
    关于线程安全和可重入的区别
    线程安全与可重入
    c++中const变量定义与头文件包含的有关问题
    extern "C"的用法解析
    gVim for windows 简单使用教程
    函数对象
    Qt核心剖析:信息隐藏
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6939599.html
Copyright © 2011-2022 走看看