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

相关推荐

  1. 134. 加油站

    2024-07-15 05:38:01       52 阅读
  2. 】134.加油站

    2024-07-15 05:38:01       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-15 05:38:01       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-15 05:38:01       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-15 05:38:01       45 阅读
  4. Python语言-面向对象

    2024-07-15 05:38:01       55 阅读

热门阅读

  1. rabbitmq解除消息者消息推送限制

    2024-07-15 05:38:01       17 阅读
  2. 迪米特法则

    2024-07-15 05:38:01       23 阅读
  3. SpringBoot+Vue实现简单的文件上传(策略模式)

    2024-07-15 05:38:01       21 阅读
  4. Zookeeper背景优缺点,以及应用场景

    2024-07-15 05:38:01       23 阅读