【代码随想录Day34】贪心算法

860 柠檬水找零

https://leetcode.cn/problems/lemonade-change/ 能找大钱时找大钱留小钱。

class Solution {
    public boolean lemonadeChange(int[] bills) {
        int fiveCount = 0, tenCount = 0;
        for (int bill : bills) {
            if (bill == 5) {
                fiveCount++;
            } else if (bill == 10) {
                tenCount++;
                if (fiveCount == 0) {
                    return false;
                } else {
                    fiveCount--;
                }
            } else {
                if (fiveCount == 0 || tenCount == 0 && fiveCount < 3) {
                    return false;
                } else if (tenCount != 0) {
                    tenCount--;
                    fiveCount--;
                } else {
                    fiveCount -= 3;
                }
            }
        }
        return true;
    }
}

406 根据身高重建队列

https://leetcode.cn/problems/queue-reconstruction-by-height/

从高到矮,依次插入,插入点的index为比它高的个数,后插入的人因为比它矮就不用管了。注意,当身高相同时,k大的人由于能放高人的范围更大需要排在k小的人的后面。

class Solution {
    public int[][] reconstructQueue(int[][] people) {
        List<int[]> queue = new LinkedList<>();
        Arrays.sort(people, (a, b) -> (Integer.compare(b[0], a[0]) == 0 ? Integer.compare(a[1], b[1]) : Integer.compare(b[0], a[0])));
        for (int[] person : people) {
            queue.add(person[1], person);
        }
        int[][] result = new int[people.length][2];
        for (int i = 0; i < people.length; i++) {
            result[i] = queue.get(i);
        }
        return result;
    }
}

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

https://leetcode.cn/problems/minimum-number-of-arrows-to-burst-balloons/

方法一: 按结束时间排序(相同时随意排),在最小结束时间插箭,已经开始的气球忽略不计,直到开始新的不重叠区间继续计数。方法二:按开始时间排序,如果和下一个区间相交,选出相交区间的结束点去更新最后一个区间的结束点;如果不相交,则需新的箭。

class Solution { //1
    public int findMinArrowShots(int[][] points) {
        Arrays.sort(points, (a, b) -> (Integer.compare(a[1], b[1])));
        int count = 1;
        int lastEnd = points[0][1];
        for (int i = 1; i < points.length; i++) {
            if (points[i][0] <= lastEnd) continue;
            count++;
            lastEnd = points[i][1];
        }
        return count;
    }
}
class Solution {  //2
    public int findMinArrowShots(int[][] points) {
        Arrays.sort(points, (a, b) -> Integer.compare(a[0], b[0]));
        int count = 1;
        for (int i = 1; i < points.length; i++) {
            if (points[i][0] <= points[i - 1][1]) {
                points[i][1] = Math.min(points[i][1], points[i - 1][1]);
            } else {
                count++;
            }
        }
        return count;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值