LeetCode—gas-station(加油站)—java

题目描述

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.

注意:

解决方案保证是唯一的.

思路解析

可以将两个数组看作一个数组,benifit[i]=gas[i]-cost[i] 即为每一段路净所得的油.

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

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

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

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

代码

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        if(gas==null||gas.length==0||cost==null||cost.length==0)
            return -1;
        int sum =0;
        int total=0;
        int pointer =0;
        for(int i=0;i<gas.length;i++){
            int diff=gas[i]-cost[i];
            sum+=diff;
            total+=diff;
            if(sum<0){
                sum=0;
                pointer = i+1;
            }
        }
        return total>=0?pointer:-1;//注意这个位置是total>=0因为刚刚好也是比较好的
    }
}


猜你喜欢

转载自blog.csdn.net/lynn_baby/article/details/80564567