Leetcode-gas-station

题目描述


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

You have a car with an unlimited gas tank and it costscost[i]of gas to travel from station i 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.

Note: 

The solution is guaranteed to be unique.

有N个加油站,第i个加油站油量为gas[i],从第i站到i+1站耗油cost[i],问从哪一站出发可以走完全程,如果没有则返回-1。

两个原则:1. 如果总total为负数,则无论如何都开不完一圈。

2. 如果从一个加油站i出发,开到加油站j所属路段的时候油耗尽,那么从i,j之间的任一个加油站出发都会在j路段或j之前路段耗尽油。

基于以上两个原则,需要一个变量total统计总剩余油量, 需要一个下标index标记起始站,初始为-1,需要一个变量sum记录油箱。一旦在过程中某个i处发现sum小于0,那么index标记为i,意味着从之前index到i之间的加油站都不能作为起始加油站。

最后,查看total是否小于0.如果是则返回-1,不是则返回index+1.

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int sum = 0;
        int total = 0;
        int index = -1;
        for(int i=0; i<gas.length; i++){
            int diff = gas[i] - cost[i];
            sum += diff;
            total += diff;
            if(sum < 0){
                index = i;
                sum = 0;
            }
        }
        return total>=0 ?index+1:-1;
    }
}

变量sum用于定义走过了k站后剩余的油量,index是标注从哪一站开始计算的。

从i=0开始往后遍历,计算sum,一旦sum<0,则表明汽车无法开到此站,所以index置为当前i,sum置0,继续计算。如果最后计算的total大于等于0,则输出index+1,因为index初始值为-1,如果遍历结束了total还是小于0,则表明无正确结果,返回-1。注意,只有sum<0后,才能进入if后的语句,index才会改变,不然index会保持在正确结果的位置。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值