代码随想录三刷day31

本文介绍了四个基于贪心策略的LeetCode题目:加油站加油路径优化、分发糖果以最大化满意度、柠檬水找零的可行性判断以及根据身高重构队列。展示了如何运用贪心思想解决实际问题。

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言


对于贪心,大多数同学都会感觉,不就是常识嘛,这算啥算法,那么本周的题目就可以带大家初步领略一下贪心的巧妙,贪心算法往往妙的出其不意。

一、力扣134. 加油站

class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int curGas = 0;
        int totalGas = 0;
        int index = 0;
        for(int i = 0; i < gas.length; i ++){
            curGas += gas[i] - cost[i];
            totalGas += gas[i] - cost[i];
            if(curGas < 0){
                curGas = 0;
                index = (i+1)%gas.length;
            }
        }
        if(totalGas < 0){
            return -1;
        }
        return index;
    }
}

二、力扣135. 分发糖果

class Solution {
    public int candy(int[] ratings) {
        int[] res = new int[ratings.length];
        Arrays.fill(res,1);
        for(int i = 1; i< ratings.length; i ++){
            if(ratings[i] > ratings[i-1] && res[i] <= res[i-1]){
                res[i] = res[i-1]+1;
            }
        }
        for(int i = ratings.length-2; i >= 0; i --){
            if(ratings[i] > ratings[i+1] && res[i] <= res[i+1]){
                res[i] = res[i+1]+1;
            }
        }
        return Arrays.stream(res).sum();
    }
}

三、力扣860. 柠檬水找零

class Solution {
    public boolean lemonadeChange(int[] bills) {
        int five = 0, ten = 0, twenty = 0;
        for(int i = 0; i < bills.length; i ++){
            switch (bills[i]){
                case 5 :
                    five ++;break;
                case 10 :
                    if(five <= 0){
                        return false;
                    }
                    five --;
                    ten ++;break;
                case 20 :
                    if(five >= 1 && ten >= 1){
                        twenty ++;
                        ten --;
                        five --;break;
                    }else if(five >= 3){
                        twenty ++;
                        five -= 3;break;
                    }else{
                        return false;
                    }
            }
        }
        return true;
    }
}

四、力扣406. 根据身高重建队列

class Solution {
    public int[][] reconstructQueue(int[][] people) {
        Arrays.sort(people,(a,b)->{
            if(a[0] == b[0]){
                return a[1] - b[1];
            }else{
                return b[0] - a[0];
            }
        });
        List<int[]> res = new ArrayList<>();
        for(int[] a: people){
            res.add(a[1],a);
        }
        return res.toArray(new int[people.length][]);
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乱世在摸鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值