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;
    }
}
相关推荐
测试19982 小时前
软件测试 - 单元测试总结
自动化测试·软件测试·python·测试工具·职场和发展·单元测试·测试用例
心中有国也有家6 小时前
cann-recipes-infer:昇腾 NPU 推理的“菜谱集合”
经验分享·笔记·学习·算法
绝知此事6 小时前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
碧海银沙音频科技研究院6 小时前
通话AEC与语音识别AEC的软硬回采链路
深度学习·算法·语音识别
csdn_aspnet7 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
一只机电自动化菜鸟8 小时前
一建机电备考笔记(40) 建筑机电施工—排水管道施工(含考频+题型)
经验分享·笔记·学习·职场和发展·课程设计
m0_629494739 小时前
LeetCode 热题 100-----26.环形链表 II
数据结构·算法·leetcode·链表
壹号用户9 小时前
用队列实现栈
数据结构·算法
做人求其滴10 小时前
面试经典 150 题 380 274
c++·算法·面试·职场和发展·力扣