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)

    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)

  • 相关阅读:
    减治算法之寻找第K小元素问题
    OpenGL的版本号历史和发展
    动态注冊监听
    Thinking in Java -- 类型信息RTTI
    Unity3D
    Oracle改动字段类型
    函数定义
    foreach
    数组
    结构体
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13407725.html
Copyright © 2011-2022 走看看