力扣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;
    }
};
相关推荐
玖釉-3 小时前
下一个排列:从字典序到原地算法的完整推导
数据结构·c++·windows·算法
IronMurphy3 小时前
【算法五十】62. 不同路径
算法
影寂ldy3 小时前
C#一维数组
算法
过期动态3 小时前
【LeetCode 热题 100】移动零
java·数据结构·算法·leetcode·职场和发展·rabbitmq
计算机安禾4 小时前
【算法分析与设计】第10篇:下界理论与NP完全性初步
大数据·人工智能·算法
水木流年追梦5 小时前
大模型入门-大模型分布式训练2
开发语言·分布式·python·算法·正则表达式·prompt
sali-tec5 小时前
C# 基于OpenCv的视觉工作流-章78-KRT测量
图像处理·人工智能·数码相机·opencv·算法·计算机视觉
菜菜的顾清寒6 小时前
力扣HOT100(32)二叉树的中序遍历
数据结构·算法·leetcode
x2c6 小时前
数据结构:线性表中链表的建立和基本操作(C)
算法