当前位置: 代码网 > it编程>软件设计>算法 > 【随想录】Day35—第八章 贪心算法 part04

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

2024年08月06日 算法 我要评论
【代码】【随想录】Day35—第八章 贪心算法 part04。


题目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- 思路

贪心思路

  • 1. 身高降序排:先根据身高进行降序排序,若身高相同,则 根据 前面有多少人升序排。
  • 2. 按照排序位置插入:构建 linkedlist ,根据排序位置,即 p[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- 思路

贪心思路

  • 先对数组根据左边界进行排序
  • for 循环遍历数组
    • ① 不重叠情况
    • ② 重叠情况
      • 将当前区间的右边界赋值为 当前遍历二者中最小的那个

遍历区间:

  • 1. 当前左边界大于前一个元素的右边界 (区间不重叠)
    • 需要对结果 res 加加
  • 2. 重叠判断
    • 若重叠,更新当前区间的右边界,使得当前区间的右边界为当前两个区间的最小值

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)

相关文章:

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

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com