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;
    }
}
相关推荐
python资深爱好者5 分钟前
Python中列表推导式的概念以及示例
开发语言·python
泡芙冰淇淋ya5 分钟前
【Spring Boot】spring boot环境搭建
java·spring boot·后端
追风筝的Coder7 分钟前
泛微开发修炼之旅--29用计划任务定时发送邮件提醒
java
欣慰的三叶草(● ̄(エ) ̄●)9 分钟前
01--SpringAI接入大模型,chatgpt,Java接入人工智能大模型
java·人工智能·chatgpt
岑梓铭21 分钟前
后端之路——阿里云OSS云存储
java·spring boot·阿里云·阿里云oss
vx_Biye_Design26 分钟前
驾校管理系统-计算机毕业设计源码49777
java·css·vue.js·spring boot·mysql·ajax·mvc
想胖的壮壮34 分钟前
python中的原子操作简介
开发语言·python
爱吃香菜¹35 分钟前
深入理解【 String类】
java·开发语言
六月的雨__38 分钟前
跑腿平台小程序的设计
java·sql·学习·小程序