LeetCode 刷题【134. 加油站】

134. 加油站

自己做(超时)

java 复制代码
class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int res = -1;

        for(int i = 0; i < gas.length; i++){
            int sum = 0;
            //顺时针走
            for(int j = 0; j < gas.length; j++){
                int index = (i + j) % gas.length;
                sum += gas[index] - cost[index];
                if(sum < 0){                             //走不到
                    sum = 0;
                    break;
                }

                if(j == gas.length - 1)                //走通了
                    res = i;
            }
            
            if(res != -1)                               //如果已经走通就没必要再走了
                break;
        }

        return res;

    }
}

看题解

官方题解

java 复制代码
class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int n = gas.length;
        int i = 0;
        while (i < n) {
            int sumOfGas = 0, sumOfCost = 0;
            int cnt = 0;
            while (cnt < n) {
                int j = (i + cnt) % n;
                sumOfGas += gas[j];
                sumOfCost += cost[j];
                if (sumOfCost > sumOfGas) {
                    break;
                }
                cnt++;
            }
            if (cnt == n) {
                return i;
            } else {
                i = i + cnt + 1;
            }
        }
        return -1;
    }
}
相关推荐
FakeOccupational1 小时前
【数学 密码学】量子通信:光的偏振&极化的量子不确定性特性 + 量子密钥分发 BB84算法步骤
算法·密码学
ZhengEnCi3 小时前
S10-蓝桥杯 17822 乐乐的积木塔
算法
贾斯汀玛尔斯3 小时前
每天学一个算法--拓扑排序(Topological Sort)
算法·深度优先
大龄程序员狗哥3 小时前
第25篇:Q-Learning算法解析——强化学习中的经典“价值”学习(原理解析)
人工智能·学习·算法
exp_add33 小时前
质数相关知识
算法
小辉同志4 小时前
215. 数组中的第K个最大元素
数据结构·算法·leetcode··快速选择
小O的算法实验室5 小时前
2025年IEEE TITS,基于矩阵的进化计算+面向无线传感器网络数据收集无人机路径规划,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
OidEncoder5 小时前
编码器分辨率与机械精度的关系
人工智能·算法·机器人·自动化
memcpy05 小时前
LeetCode 2615. 等值距离和【相同元素分组+前缀和;考虑距离和的增量】中等
算法·leetcode·职场和发展
炽烈小老头5 小时前
【 每天学习一点算法 2026/04/22】四数相加 II
学习·算法