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;
    }
}
相关推荐
皮皮林5514 小时前
拒绝写重复代码,试试这套开源的 SpringBoot 组件,效率翻倍~
java·spring boot
归去_来兮5 小时前
拉格朗日插值算法原理及简单示例
算法·数据分析·拉格朗日插值
顺风尿一寸7 小时前
从 Java NIO poll 到 Linux 内核 poll:一次系统调用的完整旅程
java
程途知微8 小时前
JVM运行时数据区各区域作用与溢出原理
java
华仔啊10 小时前
为啥不用 MP 的 saveOrUpdateBatch?MySQL 一条 SQL 批量增改才是最优解
java·后端
千寻girling12 小时前
Python 是用来做 AI 人工智能 的 , 不适合开发 Web 网站 | 《Web框架》
人工智能·后端·算法
xiaoye201812 小时前
Lettuce连接模型、命令执行、Pipeline 浅析
java
颜酱15 小时前
一步步实现字符串计算器:从「转整数」到「带括号与优化」
javascript·后端·算法
beata15 小时前
Java基础-18:Java开发中的常用设计模式:深入解析与实战应用
java·后端
Seven9716 小时前
剑指offer-81、⼆叉搜索树的最近公共祖先
java