134. 加油站

解法1

暴力模拟 + 缓存

走过的路,没走通。说明:中间节点也是不通的。

java 复制代码
class Solution {

    boolean[] visited;

    private boolean canComplete(int[] gas, int[] cost, int start) {
        if (visited[start]) {
            return false;
        }
        int n = gas.length;
        int totalGas = 0;
        int now = start;
        while (true) {
            visited[now] = true;
            totalGas += gas[now];
            if (totalGas < cost[now]) {
                return false;
            }
            totalGas -= cost[now];
            now++;
            if (now == n) {
                now = 0;
            }
            if (now == start) {
                return true;
            }
        }
    }

    public int canCompleteCircuit(int[] gas, int[] cost) {
        int n = gas.length;
        visited = new boolean[n];
        for (int start = 0; start < n; start++) {
            if (canComplete(gas, cost, start)) {
                return start;
            }
        }
        return -1;
    }
}

解法2

走过的路,没走通。说明:中间节点也是不通的。

优化效率。

java 复制代码
class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int n = gas.length;
        for (int i = 0; i < n; i++) {
            gas[i] -= cost[i];
        }
        for (int start = 0; start < n; start++) {
            int totalGas = 0, now = start, next = start;
            while (true) {
                if (now > next) {
                    next = now;
                }
                totalGas += gas[now++];
                if (totalGas < 0) {
                    break;
                }
                if (now == n) {
                    now = 0;
                }
                if (now == start) {
                    return now;
                }
            }
            start = next;
        }
        return -1;
    }
}
相关推荐
aWty_20 小时前
实分析入门(12)--可测函数
学习·数学·算法·实变函数
Leo18721 小时前
分布式事务
java·分布式·分布式事务
RSTJ_162521 小时前
PYTHON+AI LLM DAY SIXTY-FOUR
开发语言·python
海砥装备HardAus21 小时前
无人机姿态解算中「重力矢量观测退化」机理与动态补偿技术
算法·无人机·飞控
广州灵眸科技有限公司21 小时前
瑞芯微RV1126B开发板(EASY-EAI-PI2) 开发套件组装上电
网络·数据库·人工智能·算法·飞书
SuperHeroWu721 小时前
【算法】强化学习中奖励和损失函数的关系
算法·环境·强化学习·损失函数·奖励
voidmort21 小时前
9. 微调(Fine-tuning)的数学原理
人工智能·算法·机器学习
覆东流21 小时前
Java开发环境搭建
java·开发语言·后端
阿洛学长21 小时前
VMware安装虚拟机教程(超详细)
java·linux·开发语言
rit843249921 小时前
链路预测(Link Prediction)MATLAB 实现
开发语言·matlab