LeetCode 134 Gas Station

There are N gas stations along a circular route, where the amount of gas at stationi isgas[i].

You have a car with an unlimited gas tank and it costscost[i] of gas to travel from stationi to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.


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


题目大意:有一个环形公路,路上有n个加油站,第i个加油站有gas[i]这么多油,从第i个加油站到第i+1个加油站需要消耗cost[i]的油,问从哪个加油站出发可以环绕行驶一周,保证答案唯一,不存在的情况下输出-1


题目分析:首先若所有加油站的总油量不比总消耗小,这种情况下解必然存在,从0位置开始,若到了某个加油站,这时候累计的油量小于消耗量了,那么显然前面的加油站都不能当做起点,因为上次我设定的起点肯定是油量大于消耗量的,往后的情况下累计油量小于消耗量了,说明这中间无论我取哪个作为起点,到当前这个加油站都会出现累积量小于消耗量的情况,因此就不断把起点设在不满足条件的点的后面那个点上,环形取个模即可。

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int len = gas.length;
        int ans = 0;
        int pos = 0;
        int sumGas = 0, sumCost = 0;
        int curGas = 0, curCost = 0;
        while(pos < len) {
            sumGas += gas[pos];
            sumCost += cost[pos];
            curGas += gas[pos];
            curCost += cost[pos];
            if(curGas < curCost) {
                ans = (pos + 1) % len;
                curGas = 0;
                curCost = 0;
            }
            pos ++;
        }
        if(sumGas < sumCost) {
            ans = -1;
        }
        return ans;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值