力扣134. 加油站

迭代

  • 思路:
    • 暴力模拟迭代;
    • 假设从第 idx 个加油站开始,使用一个变量对行驶的加油站个数计数,如果最后行驶的个数为 size,则是可行的;
    • 否则,行驶过的加油站都不可行;(加快更新 idx 重试)
      • 是否可行,通过累计获取的汽油容量与消耗的容量进行比较,Sum(gasi) > Sum(costi);
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;
    }
};
相关推荐
fkyyly13 小时前
hermes解读
算法·code_agent
过期的秋刀鱼!13 小时前
使用都热编码的分类特征
人工智能·算法·决策树·机器学习·分类·数据挖掘
wabs66614 小时前
关于哈希表【力扣383.赎金信的思考】
算法·leetcode·散列表
love_muming14 小时前
二叉树操作全解析:从递归到层序遍历
java·数据结构·算法·二叉树
.道阻且长.1 天前
2.LeetCode算法习题讲解--双指针--复写零
算法·leetcode·职场和发展
To_OC1 天前
LC 438 找到所有字母异位词:暴力超时后,我靠滑动窗口一招搞定
javascript·算法·leetcode
Forever Nore1 天前
学完C语言力扣第一题做不来正常吗
数据结构·算法
hansang_IR1 天前
【题解】LC:倍增 / 区间并查集(Range Parallel Unionfind)
c++·算法·并查集
Tisfy1 天前
LeetCode 3731.找出缺失的元素:哈希 / 排序
算法·leetcode·哈希算法·排序·哈希表