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;
    }
}
相关推荐
花生了什么事o4 分钟前
JVM 垃圾回收:对象如何被判定和回收
java·jvm
evans在进步19 分钟前
HashMap 为什么线程不安全?ConcurrentHashMap 如何解决?
java·spring boot·spring
我命由我1234530 分钟前
匈牙利命名法
java·服务器·后端·学习·java-ee·kotlin·学习方法
闲猫34 分钟前
LangChain / Integrations / Integrations by component / Tool
java·数据库·langchain
小田的博客35 分钟前
SAP MM 供应商银行主数据更新报错!message R1228!
android·java·服务器
吹什么轩1 小时前
c++复习:map和set的使用
开发语言·c++
必须得开心呀1 小时前
qt生成dump文件并定位异常
开发语言·qt
范什么特西1 小时前
知识总结03
java
fpcc1 小时前
跟我学C++中级篇—内存流
开发语言·c++