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;
    }
}
相关推荐
To_OC4 小时前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员
千纸鹤安安9 小时前
千问Qwen-AgentWorld来了:一个语言模型搞定七大Agent场景,GPT-5.4都输了
算法
白鲸开源11 小时前
Apache SeaTunnel Zeta Engine 的 Basic Auth 是怎么工作的?
java·vue.js·github
白鲸开源11 小时前
一文读懂DolphinScheduler插件机制:如何轻松扩展任务类型与数据源
java·架构·github
七牛开发者11 小时前
MCP 到底是什么?为什么 Agent 都想接上它
算法·aigc·agent
用户2986985301416 小时前
Java 实现 Word 文档文本查找与高亮标注
java·后端
宇宙之一粟17 小时前
乐企版式文件生成平台
java·后端·python
plainGeekDev17 小时前
MVC 写法 → MVVM
android·java·kotlin