贪心day4

406. 根据身高重建队列

class Solution {
    public int[][] reconstructQueue(int[][] people) {
        //问题设计两个维度 h和k 需先确定一个维度 再来考虑解决另一个维度
        //k不能先解决,因为k的合理性有h确定 所以先解决h
        //身高由大到小排列 使用lamda写一个比较器 会根据指定的比较器引发的顺序对指定的对象数组进行排序
        Arrays.sort(people, (i, j) -> {
            //如果相等 则按k从小到大排 这样k小的就给k大的贡献了一份力量
            if (i[0] == j[0]) return i[1] - j[1];
            return j[0] - i[0];
        });
        // Arrays.sort(people, new Comparator<int[]>() {
        //     public int compare(int[] a, int[] b) {
        //         if (a[0] == b[0]) return a[1] - b[1];
        //         return b[0] - a[0];
        //     }
        // });
        List<int[]> res = new ArrayList<>();
        for (int[] person : people) {
            //身高高的小排 身高相较来说矮的 排的位置一定符合要求
            res.add(person[1], person);
        }
        return res.toArray(new int[people.length][]);
    }
}

452. 用最少数量的箭引爆气球

class Solution {
    public int findMinArrowShots(int[][] points) {
        int len= points.length;
        if (len == 1) return 1;
        //按右从左到右排
        Arrays.sort(points, (a, b) -> Integer.compare(a[1], b[1]));
        int res = 1, overlapEnd = points[0][1];
        for (int i = 1; i < len; i++) {
            //如果p起点大于前一个重叠区间的尾部 则需要新的箭矢
            //已经按右边界排序 前一个如果与后一个右重叠 重叠区域的右边界一定是前面最开始元素右边界
            if (points[i][0] > overlapEnd) {
                overlapEnd = points[i][1];
                res++;
            }
        }
        return res;
    }
}

参考:programmercarl.com

          https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons/solution/yong-zui-shao-shu-liang-de-jian-yin-bao-qi-qiu-1-2/

posted @ 2022-05-04 19:02  一梦两三年13  阅读(16)  评论(0)    收藏  举报