• 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)

  • 相关阅读:
    canvas实现音乐中的歌词播放效果
    canvas调节视频颜色
    clip API实现遮罩
    总有那么几款发型 是经典不过时的
    很多人喜欢露脚踝你觉得时尚吗?
    王者荣耀花木兰攻略解析
    十位王者给出的单排心得
    IntelliJ IDEA2017 + tomcat 即改即生效 实现热部署
    IntelliJ IDEA2017 + tomcat 即改即生效 实现热部署
    jqGrid分页查询出错
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13407725.html
Copyright © 2020-2023  润新知