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;
    }
}
相关推荐
碧海银沙音频科技研究院15 分钟前
基于炬芯ATS308X的DNN全连接神经网络手写数字识别系统设计
人工智能·深度学习·算法
文丑颜不良啊21 分钟前
LeetCode601~625题目解析
java·leetcode
stolentime29 分钟前
SOS DP学习笔记
c++·笔记·学习·算法·贪心算法·动态规划·二进制
文丑颜不良啊30 分钟前
LeetCode651~675题目解析
java·leetcode
水母量化33 分钟前
量化收益率计算别混用:算术均值、几何均值与对数收益
算法·均值算法·量化交易
yuanxi2001 小时前
华宝股份山东嘉萃投产,销售如何接住产能节奏
职场和发展·创业创新·学习方法
Xin7701 小时前
LeetCode 78. 子集(回溯法)
leetcode
xunberg1 小时前
【生命科学 Agent】推理平台(三)
算法·程序员·架构
INGNIGHT1 小时前
151 · 买卖股票的最佳时机 III(序列dp)
数据结构·算法·leetcode
庖丁解牛1 小时前
十进制转二进制:凑数法(填1法)
算法