算法训练营第三十五天|860.柠檬水找零、406.根据身高重建队列、452. 用最少数量的箭引爆气球

37 阅读1分钟

860. 柠檬水找零

class Solution {
    public boolean lemonadeChange(int[] bills) {
        int five = 0;
        int ten = 0;
        for(int b : bills){
            if(b == 5)five++;
            else if(b == 10){
                ten++;
                five--;
            }
            else if(b == 20){
                if(ten > 0){
                    ten--;
                    five--;
                }
                else{
                    five -= 3;
                }
            }
            if(five < 0)return false;
        }
        return true;
    }
}

406. 根据身高重建队列

一般这种数对,还涉及排序的,根据第一个元素正向排序,根据第二个元素反向排序,或者根据第一个元素反向排序,根据第二个元素正向排序,往往能够简化解题过程。

在本题目中,首先对数对进行排序,按照数对的元素 1 降序排序,按照数对的元素 2 升序排序。原因是:按照元素 1 进行降序排序,对于每个元素,在其之前的元素的个数,就是大于等于他的元素的数量,而按照第二个元素正向排序,我们希望 k 大的尽量在后面,减少插入操作的次数。

class Solution {
    public int[][] reconstructQueue(int[][] people) {
        Arrays.sort(people, (a, b) -> {
            if(a[0] == b[0])return a[1] - b[1]; // 第一个元素相等时,对第二个元素升序排列
            return b[0] - a[0];// 对第一个元素降序排列
        });

        LinkedList<int[]> queue = new LinkedList<>();
        for(int[] p : people){
            queue.add(p[1], p); // Linkedlist.add(index, value),会将value插入到指定index里
        }

        return queue.toArray(new int[people.length][]);
    }
}

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

class Solution {
    public int findMinArrowShots(int[][] points) {
        // 按照56题思路把区间合并,然后计算有几个不重叠的区间,就是最少需要几支箭
        // 边界重叠的话只能合二为一,不能全合成一个,所以合并时,重叠区间的右边界要更新为其最小右边界
        // 换句话说,如果气球重叠了,重叠气球中右边边界的最小值之前的区间一定需要一个弓箭。
        
        // 排序
        Arrays.sort(points, (a, b) -> Integer.compare(a[0], b[0]));

        LinkedList<int[]> res = new LinkedList<>();
        res.add(points[0]);
        for(int i = 1; i < points.length; i++){
            int[] curr = points[i];
            int[] last = res.getLast();
            if(last[1] >= curr[0]){
                last[1] = Math.min(last[1], curr[1]);
            }
            else{
                res.add(curr);
            }
        }
        return res.size();
    }
}