代码随想录Day35 | 860. 柠檬水找零、406. 根据身高重建队列、452. 用最少数量的箭引爆气球 | 贪心

46 阅读1分钟

860. 柠檬水找零

题目链接:860. 柠檬水找零

思路: 10块可以用一个5块来找零,20块可以用1个10块和一个5块或者3个五块,优先使用10来找零,因为10只能用于20找零,而5既能用于10,又能用于20。

class Solution {
    public boolean lemonadeChange(int[] bills) {
        int count5 = 0, count10 = 0;
        for (int i = 0; i < bills.length; i++) {
            if (bills[i] == 5) {
                count5++;
            } else if (bills[i] == 10) {
                count5--;
                count10++;
            } else if (bills[i] == 20) {
                if (count10 > 0) {
                    count5--;
                    count10--;
                } else {
                    count5 -= 3;
                }
            }
            if (count5 < 0 || count10 < 0) return false;
        }
        return true;
    }
}

406. 根据身高重建队列

题目链接:406. 根据身高重建队列

思路: 身高从大到小排(身高相同的话则k小的站前面),让高个子在前面,只需要按照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[]> que = new LinkedList<>();

        for (int[] p : people) {
            que.add(p[1],p);
        }

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

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

题目链接:452. 用最少数量的箭引爆气球

思路: 计算若干区间中最多有几个互不相交的区间
1、从区间集合 intvs 中选择一个区间 x,这个 x 是在当前所有区间中end 最小的。
2、把所有与 x 区间相交的区间从区间集合 intvs 中删除。
3、重复步骤 1 和 2,直到 intvs 为空为止。之前选出的那些 x 就是最大不相交子集。

class Solution {
    public int findMinArrowShots(int[][] points) {
        Arrays.sort(points, (a, b) -> a[1] < b[1] ? -1 : 1);
        int count = 1;
        int end = points[0][1];
        for (int[] point : points) {
            if (point[0] > end) {
                count++;
                end = point[1];
            }
        }
        return count;
    }
}