it编程 > 软件设计 > 算法

【随想录】Day35—第八章 贪心算法 part04

107人参与 2024-08-06 算法


题目1: 柠檬水找零


1- 思路

贪心思路


2- 题解

⭐ 柠檬水找零 ——题解思路

在这里插入图片描述

class solution {
    public boolean lemonadechange(int[] bills) {
        int[] moneycount = new int[3];
        for(int i = 0 ; i < bills.length;i++){
            if(bills[i]==5){
                moneycount[0]++;
            }else if (bills[i]==10){
                moneycount[1]++;
                moneycount[0]--;
            }else if(bills[i]==20){
                if(moneycount[1] > 0){
                    moneycount[1]--;
                    moneycount[0]--;
                }else{
                    moneycount[0]-=3;
                }
            }
            if(moneycount[0]<0 || moneycount[1]<0){
                return false;
            }
        }
        return true;
    }
}

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


1- 思路

贪心思路


2- 题解

⭐ 根据身高重建队列 ——题解思路

在这里插入图片描述

class solution {
    public int[][] reconstructqueue(int[][] people) {
        arrays.sort(people,(o1,o2)->{
            if(o1[0]==o2[0]) return o1[1]-o2[1];
            return o2[0]-o1[0];
        }
        );

        list<int[]> res = new linkedlist<>();
        for(int[] n:people){
            res.add(n[1],n);
        }

        return res.toarray(new int[res.size()][]);
    }
}

题目3: 用最少数量的箭引爆气球


1- 思路

贪心思路

遍历区间:


2- 题解

⭐ 用最少数量的箭引爆气球 ——题解思路

在这里插入图片描述

class solution {
    public int findminarrowshots(int[][] points) {
        arrays.sort(points,(o1,o2) -> integer.compare(o1[0],o2[0]));
        int res = 1;
        for(int i = 1 ; i < points.length;i++){
            if(points[i-1][1] < points[i][0]){
                res++;
            }else{
                points[i][1] = math.min(points[i-1][1],points[i][1]);
            }
        }
        return res;
    }
}

(0)

您想发表意见!!点此发布评论

推荐阅读

算法学习笔记(7)-贪心算法

08-06

贪心算法笔记

08-06

Day 37 贪心算法 6

08-06

codeforces签到题之div4

08-06

利用贪心算法求解地图着色问题

08-06

【算法刷题 | 贪心算法09】4.30(单调递增的数字)

08-06

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论