ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

力扣134. 加油站

2026/10/3 13:08:39 拓冰建站 浏览量
力扣134. 加油站

迭代

  • 思路:
    • 暴力模拟迭代;
    • 假设从第 idx 个加油站开始,使用一个变量对行驶的加油站个数计数,如果最后行驶的个数为 size,则是可行的;
    • 否则,行驶过的加油站都不可行;(加快更新 idx 重试)
      • 是否可行,通过累计获取的汽油容量与消耗的容量进行比较,Sum(gas[i]) > Sum(cost[i]);
class Solution {
public:int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {int size = gas.size();int idx = 0;while (idx < size) {int sumOfGas = 0;int sumOfCost = 0;int cnt = 0;while (cnt < size) {int j = (idx + cnt) % size;sumOfGas += gas[j];sumOfCost += cost[j];if (sumOfCost > sumOfGas) {break;}cnt++;}if (cnt == size) {return idx;} else {idx = idx + cnt + 1;}}return -1;}
};