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;
    }
}
相关推荐
JIngJaneIL4 分钟前
基于java + vue校园快递物流管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js
超级大只老咪8 分钟前
数组的正向存储VS反向存储(Java)
java·开发语言·python
柏木乃一9 分钟前
进程(2)进程概念与基本操作
linux·服务器·开发语言·性能优化·shell·进程
毕设源码-赖学姐14 分钟前
【开题答辩全过程】以 基于JSP的物流信息网的设计与实现为例,包含答辩的问题和答案
java·开发语言
Honmaple14 分钟前
Spring AI 2.x 发布:全面拥抱 Java 21,Redis 史诗级增强
java·人工智能·spring
leo__52015 分钟前
基于LDA的数据降维:原理与MATLAB实现
开发语言·matlab·信息可视化
asdfg125896321 分钟前
JS中的闭包应用
开发语言·前端·javascript
代码or搬砖1 小时前
Java集合-Set讲解
java·开发语言
艾上编程1 小时前
第三章——爬虫工具场景之Python爬虫实战:学术文献摘要爬取,助力科研高效进行
开发语言·爬虫·python