算法跟学Day35【代码随想录】

本文介绍了三个使用贪心算法解决的LeetCode问题:860.柠檬水找零,通过管理5元和10元硬币找零;406.根据身高重建队列,按特定规则排序人数组;452.用最少数量的箭引爆气球,确定最少的射击次数。每个问题都提供了Java代码实现。
摘要由CSDN通过智能技术生成

第八章 贪心算法 part04

大纲

● 860.柠檬水找零
● 406.根据身高重建队列
● 452. 用最少数量的箭引爆气球

leetcode 860 柠檬水找零

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

leetcode 406 根据身高重建队列

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);
        return queue.toArray(new int[queue.size()][]);
    }
}

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

class Solution {
    public int findMinArrowShots(int[][] points) {
        int res = 1;
        Arrays.sort(points, (a, b) -> Integer.compare(a[0], b[0]));
        for (int i = 1; i < points.length; i++) {
            if (points[i][0] > points[i - 1][1]) res++;
            else points[i][1] = Math.min(points[i][1], points[i - 1][1]);
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值