代码随想录算法训练营第29天 | 134. 加油站 135. 分发糖果 860.柠檬水找零 406.根据身高重建队列

134. 加油站

代码随想录

class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int curSum = 0;
        int totalSum = 0;
        int start = 0;
        for(int i = 0;i < gas.length;i++){
            curSum += gas[i] - cost[i];
            totalSum += gas[i] - cost[i];
            if(curSum < 0){
                start = i + 1;
                curSum = 0;
            }
        }
        if(totalSum < 0)return -1;
        else return start;
    }
}

135. 分发糖果

135. 分发糖果 - 力扣(LeetCode)

本题涉及到一个思想,就是想处理好一边再处理另一边,不要两边想着一起兼顾,后面还会有题目用到这个思路

代码随想录

先从左往右遍历,右比左大就赋值2,其他赋值1

再从右往左遍历,左比右大就比右边的值多1,取最大值

class Solution {
    public int candy(int[] ratings) {
        int len = ratings.length;
        int[] candy = new int[len];
        candy[0] = 1;
        //右比左大
        for(int i = 1;i < len;i++){
            if(ratings[i - 1] < ratings[i])candy[i] = candy[i - 1] + 1;
            else candy[i] = 1;//漏了
        }
        
        //左比右大
        for(int i = len - 1;i >= 1;i--){
            if(ratings[i - 1] > ratings[i])candy[i - 1] = Math.max(candy[i] + 1,candy[i - 1]);
        }
        int sum = 0;
        for(int c:candy){
            sum += c;
        }
        return sum;
    }
}

860.柠檬水找零

860. 柠檬水找零 - 力扣(LeetCode)

代码随想录

付20优先找10+5,然后找3*5

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

406.根据身高重建队列

406. 根据身高重建队列 - 力扣(LeetCode)

本题有点难度,和分发糖果类似,不要两头兼顾,处理好一边再处理另一边。

代码随想录

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[]> que = new LinkedList<>();
        for(int[] p:people){
            que.add(p[1],p);//Linkedlist.add(index, value),會將value插入到指定index裡
        }
        return que.toArray(new int[que.size()][]);
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值