首页 > 其他 > 详细

LeetCode 134 加油站

时间:2020-08-22 18:32:52      阅读:66      评论:0      收藏:0      [点我收藏+]

LeetCode 134 加油站

在一条环路上有?N?个加油站,其中第?i?个加油站有汽油?gas[i]?升。
你有一辆油箱容量无限的的汽车,从第i个加油站开往第 i+1?个加油站需要消耗汽油?cost[i]?升。你从其中的一个加油站出发,开始时油箱为空。
如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1
说明:

  • 如果题目有解,该答案即为唯一答案。
  • 输入数组均为非空数组,且长度相同。
  • 输入数组中的元素均为非负数。
    暴力法: 以每个加油站为起点循环一次,O(N2)

执行用时:127 ms, 在所有 Java 提交中击败了15.05%的用户
内存消耗:39.8 MB, 在所有 Java 提交中击败了90.77%的用户

class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        if(gas==null || gas.length==0 || cost==null || cost.length==0) {
            return -1;
        }else if(gas.length==1 && cost.length==1) {
            return gas[0]>=cost[0]? 0:-1;
        }

        //在每个加油站,拥有: 剩余汽油rem、汽油gas[i]
        for(int i=0; i<gas.length; i++) {
            if(aux(gas, cost, i)) {
                return i;
            }
        }
        return -1;
    }

    //从start号加油站出发能否环绕一圈
    public boolean aux(int[] gas, int[] cost, int start) {
        int rem = 0;
        int currGas = rem + gas[start];
        // System.out.println("start="+start);
        for(int i=start; i<gas.length+(start-1)+1; i++) {
            // System.out.println("curr="+(i%gas.length)+"  gas="+currGas);
            //当前站点最大汽油储备不够到下一站
            if(currGas < cost[i%gas.length]) {
               return false; 
            }
            //更新下一站点的汽油储备
            currGas += gas[(i+1)%gas.length] - cost[i%gas.length];   
        }

        return true;
    }
}

LeetCode 134 加油站

原文:https://www.cnblogs.com/CodeSPA/p/13546368.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!