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;
    }
}
相关推荐
Tingjct1 天前
十大排序算法——交换排序(一)
c语言·开发语言·数据结构·算法·排序算法
MM_MS1 天前
Halcon图像点运算、获取直方图、直方图均衡化
图像处理·人工智能·算法·目标检测·计算机视觉·c#·视觉检测
每天要多喝水1 天前
贪心算法专题Day22
算法·贪心算法
ujainu1 天前
Flutter + OpenHarmony 游戏开发进阶:动态关卡生成——随机圆环布局算法
算法·flutter·游戏·openharmony
PPPPPaPeR.1 天前
程序地址空间
linux·算法
苦藤新鸡1 天前
51.课程表(拓扑排序)-leetcode207
数据结构·算法·leetcode·bfs
senijusene1 天前
数据结构与算法:栈的基本概念,顺序栈与链式栈的详细实现
c语言·开发语言·算法·链表
naruto_lnq1 天前
分布式日志系统实现
开发语言·c++·算法
啊我不会诶1 天前
Codeforces Round 1071 (Div. 3) vp补题
开发语言·学习·算法