[Java][Leetcode middle] 134. 加油站

方法一,自己想的,超时

双重循环

从第一个点开始循环尝试,

如果最终能走到终点,说明可行。

java 复制代码
public int canCompleteCircuit(int[] gas, int[] cost) {
        int res = -1;
        int n = gas.length;

        int remainGas;
        int j;
        for (int i = 0; i < n; i++) {
            remainGas = 0;
            for (j = i; j < n + i; j++) {
                int tmp = j;
                if (tmp >= n) {
                    tmp = tmp - n;
                }
                remainGas += gas[tmp] - cost[tmp];
                if (remainGas < 0) {
                    break;
                }
            }
            if (j == n + i) {
                res = i;
                break;
            }
        }
        return res;
    }

方法二,官方题解

利用结论:

假设x到不了y+1,那么[x,y]中的任意一个节点都无法到达y+1。那么循环直接从y+1开始即可

改造我们的代码

java 复制代码
public int canCompleteCircuit(int[] gas, int[] cost) {
        int res = -1;
        int n = gas.length;

        int remainGas;
        int cnt = 0;
        int tmp = 0;
        for (int i = 0; i < n; i++) {
            remainGas = 0;
            for (cnt = 0; cnt < n; cnt++) {
                tmp = (i + cnt)%n;
                remainGas += gas[tmp] - cost[tmp];
                if (remainGas < 0) {
                    break;
                }
            }
            if (cnt == n) {
                res = i;
                break;
            }else {
                i = i + cnt;
            }
        }
        return res;
    }

评论区做法

利用唯一解的特性;

使用一次遍历,如果存在解,那么解一定出现在最耗油的一段路之后。

java 复制代码
    public int canCompleteCircuit3(int[] gas, int[] cost) {
        int res = -1;
        int n = gas.length;

        int remainGas = 0;
        int minRemain = Integer.MAX_VALUE;
        int use = 0;
        for (int i = 0; i < n; i++) {
            use = gas[i] - cost[i];
            remainGas += use;
            if (remainGas <  minRemain) {
                minRemain = remainGas;
                res = i;
            }
        }

        if(remainGas >= 0){
            return (res + 1)%n;
        }else {
            return -1;
        }
    }
相关推荐
xuxie139 分钟前
SpringBoot文件下载(多文件以zip形式,单文件格式不变)
java·spring boot·后端
重生成为编程大王36 分钟前
Java中的多态有什么用?
java·后端
666和77737 分钟前
Struts2 工作总结
java·数据库
中草药z42 分钟前
【Stream API】高效简化集合处理
java·前端·javascript·stream·parallelstream·并行流
Lris-KK1 小时前
【Leetcode】高频SQL基础题--1731.每位经理的下属员工数量
sql·leetcode
野犬寒鸦1 小时前
力扣hot100:搜索二维矩阵 II(常见误区与高效解法详解)(240)
java·数据结构·算法·leetcode·面试
zru_96021 小时前
centos 系统如何安装open jdk 8
java·linux·centos
菜鸟得菜1 小时前
leecode kadane算法 解决数组中子数组的最大和,以及环形数组连续子数组的最大和问题
数据结构·算法·leetcode
LiRuiJie1 小时前
深入剖析Spring Boot / Spring 应用中可自定义的扩展点
java·spring boot·spring