0
点赞
收藏
分享

微信扫一扫

用极限思维秒破134. 加油站 -LeetCode算法

哈哈我是你爹呀 2022-03-30 阅读 78
算法

题目:134. 加油站

在一条环路上有 n 个加油站,其中第 i 个加油站有汽油 gas[i] 升。
你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。
给定两个整数数组 gas 和 cost ,如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1 。如果存在解,则 保证 它是 唯一 的。

链接:https://leetcode-cn.com/problems/gas-station

理解与解答:

对于能否走完一圈那里,可以采用"极限模式“的思考方式:
1,如果加油量gas[]数组和无限小,耗油量cost[]数组和无限大,那么必然无法走完一圈: (汽车开到半路没油了,没法绕圈回家,哭了~);
2,如果加油量gas[]数组和无限大,耗油量cost[]数组和无限小,那么必然可以走完一圈 (汽车用无限的油量走一个无限小的圆圈,so easy~)。

其实在很多算法的难理解的地方,采用"极限思维"就能秒理解。
在这里插入图片描述
利用极限思维理解。
在这里插入图片描述

class Solution {
    /**
       采用极限思维秒破 
     */
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int gasSum = 0;
        int costSum = 0;
        
        for (int g = 0; g < gas.length; g++) {
            gasSum += gas[g];
        }
        for (int c = 0; c < cost.length; c++) {
            costSum += cost[c];
        }
        // 只要中间有一个无限大的路程,有限的油必然被耗光
        if (gasSum < costSum) {
            return -1;
        }

        // 上方不能走完圈,下方必然存在一个能走完圈的
        int restGas = 0; // 剩余油量
        int start = 0;
        for (int i = 0; i < gas.length; i++) {
            restGas = restGas + gas[i] - cost[i]; // 剩余油量+本站油量 - 下一段路程油耗
            if (restGas < 0) { // 没有办法到达下一站,那么就尝试将下一站作为起点,万一下一站有无限的油量呢~
                restGas = 0;
                start = i + 1; 
            }
        }
        return start;
    }
}
/**
    https://leetcode-cn.com/problems/gas-station/solution/tan-xin-dong-hua-tu-jie-dai-ma-jian-ji-b-na6b/
 */

参考来源:
https://leetcode-cn.com/problems/gas-station/solution/tan-xin-dong-hua-tu-jie-dai-ma-jian-ji-b-na6b/
https://xiaochen1024.com/courseware/60b4f11ab1aa91002eb53b18/61963ce5c1553b002e57bf14

举报

相关推荐

0 条评论