力扣134. 加油站

迭代

  • 思路:
    • 暴力模拟迭代;
    • 假设从第 idx 个加油站开始,使用一个变量对行驶的加油站个数计数,如果最后行驶的个数为 size,则是可行的;
    • 否则,行驶过的加油站都不可行;(加快更新 idx 重试)
      • 是否可行,通过累计获取的汽油容量与消耗的容量进行比较,Sum(gas[i]) > Sum(cost[i]);
cpp 复制代码
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;
    }
};
相关推荐
tankeven1 分钟前
HJ138 在树上游玩
c++·算法
lihihi34 分钟前
P1209 [USACO1.3] 修理牛棚 Barn Repair
算法
weixin_387534221 小时前
Ownership - Rust Hardcore Head to Toe
开发语言·后端·算法·rust
xsyaaaan1 小时前
leetcode-hot100-链表
leetcode·链表
庞轩px1 小时前
MinorGC的完整流程与复制算法深度解析
java·jvm·算法·性能优化
Queenie_Charlie1 小时前
Manacher算法
c++·算法·manacher
闻缺陷则喜何志丹1 小时前
【树的直径 离散化】 P7807 魔力滋生|普及+
c++·算法·洛谷·离散化·树的直径
AI_Ming1 小时前
Seq2Seq-大模型知识点(程序员转行AI大模型学习)
算法·ai编程
若水不如远方1 小时前
分布式一致性(六):拥抱可用性 —— 最终一致性与 Gossip 协议
分布式·后端·算法
计算机安禾1 小时前
【C语言程序设计】第35篇:文件的打开、关闭与读写操作
c语言·开发语言·c++·vscode·算法·visual studio code·visual studio