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;
    }
}
相关推荐
whm27774 分钟前
Visual Basic 参数传送-形参与实参
开发语言·visual studio
9号达人13 分钟前
if-else 优化的折中思考:不是消灭分支,而是控制风险
java·后端·面试
共享家952716 分钟前
QT-常用控件(多元素控件)
开发语言·前端·qt
幸运小圣16 分钟前
Iterator迭代器 【ES6】
开发语言·javascript·es6
葱头的故事18 分钟前
将传给后端的数据转换为以formData的类型传递
开发语言·前端·javascript
远远远远子33 分钟前
C++-- 内存管理
c++·算法
不知道累,只知道类33 分钟前
Java 在AWS上使用SDK凭证获取顺序
java·aws
sprintzer1 小时前
10.6-10.15力扣模拟刷题
算法·leetcode·职场和发展
徐子童1 小时前
算法---队列+宽搜
算法··队列·层序遍历
咖啡Beans1 小时前
SpringBoot2.7集成Swagger3.0
java·swagger