217.贪心算法:加油站(力扣)

代码解决

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) 
    {
        int curtotol = 0; // 当前累积油量
        int tatol = 0; // 总的油量减去总的花费油量
        int start = 0; // 起始加油站的索引

        // 遍历所有加油站
        for (int i = 0; i < gas.size(); i++)
        {
            curtotol += gas[i] - cost[i]; // 计算当前累积油量
            tatol += gas[i] - cost[i]; // 计算总的油量减去总的花费油量

            // 如果当前累积油量小于0,则无法到达下一个加油站
            if (curtotol < 0)
            {
                start = i + 1; // 重置起点为下一个加油站
                curtotol = 0; // 重置当前累积油量
            }
        }

        // 如果总的油量小于总的花费油量,则无法完成环路
        if (tatol < 0) return -1;

        // 返回起始加油站的索引
        return start;
    }
};

核心思想

  1. 遍历每个加油站
    • 计算从当前起点开始的累积油量。如果累积油量不足以到达下一个加油站,则从下一个加油站重新开始。
    • 如果总的油量 tatol 小于总的花费油量,说明无论从哪个加油站出发都无法绕环路一周,直接返回 -1
    • 否则,返回最后一次重置起点的位置 start

假设 gas = [1, 2, 3, 4, 5]cost = [3, 4, 5, 1, 2]

  1. 遍历加油站:

    • i = 0: curtotol = 1 - 3 = -2, tatol = -2, start = 1, curtotol = 0
    • i = 1: curtotol = 2 - 4 = -2, tatol = -4, start = 2, curtotol = 0
    • i = 2: curtotol = 3 - 5 = -2, tatol = -6, start = 3, curtotol = 0
    • i = 3: curtotol = 4 - 1 = 3, tatol = -3
    • i = 4: curtotol = 5 - 2 = 6, tatol = 0
  2. 最终 tatol >= 0,返回 start = 3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

清酒。233

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

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

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

打赏作者

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

抵扣说明:

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

余额充值