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;
    }
}
相关推荐
comli_cn2 小时前
残差链接(Residual Connection)
人工智能·算法
Aaron15882 小时前
基于VU13P在人工智能高速接口传输上的应用浅析
人工智能·算法·fpga开发·硬件架构·信息与通信·信号处理·基带工程
予枫的编程笔记3 小时前
【论文解读】DLF:以语言为核心的多模态情感分析新范式 (AAAI 2025)
人工智能·python·算法·机器学习
im_AMBER3 小时前
Leetcode 99 删除排序链表中的重复元素 | 合并两个链表
数据结构·笔记·学习·算法·leetcode·链表
王老师青少年编程3 小时前
信奥赛C++提高组csp-s之欧拉回路
c++·算法·csp·欧拉回路·信奥赛·csp-s·提高组
墨有6663 小时前
数学分析栈的出栈顺序:从算法判断到数学本质(卡特兰数初探)
c++·算法·数学建模
zhutoutoutousan3 小时前
氛围数学学习:用游戏化思维征服抽象数学
学习·算法·游戏
西伯利亚狼_J20203 小时前
资料260107J-Go
职场和发展
guygg883 小时前
基于捷联惯导与多普勒计程仪组合导航的MATLAB算法实现
开发语言·算法·matlab
fengfuyao9853 小时前
遗传算法与粒子群算法求解非线性函数最大值问题
算法