【随想录】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;
    }
}

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值