LeetCode#134. Gas Station

  • 题目:一个环形加油站,第i个站存有汽油gas[i],从第i个加油站到第i+1个需要花费汽油cost[i].从环形加油站找到一个起始位置,使得能完成整个环形行程。如果不存在这样的一个路径,则返回-1。
  • 思路:

    1.如果总共的汽油>=总共的花费,说明一个存在一条满足条件的路径。
    
    2.默认设置起点为第0个位置,如果起点能够到达第i个点,则到达第i个点时汽油剩余量>=0,否则起点重新设置为i+1
    
  • 难度:Medium
  • 代码:
public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        if(gas == null || gas.length == 0 || cost == null || cost.length == 0){
            return -1;
        }
        int tank = 0;
        int sumGas = 0;
        int sumCost = 0;
        int start = 0;
        for(int i = 0; i < gas.length; i++){
            sumGas += gas[i];
            sumCost += cost[i];
            tank = tank + gas[i] - cost[i];
            //如果tank>=0,说明从start位置出发,能到达第i个位置
            if(tank < 0){
                start = i + 1;
                tank = 0;
            }
        }
        //如果sumGas >= sumCost,则一定存在一个路径能够走完这个环
        if(sumGas < sumCost){
            return -1;
        }else{
            return start;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/u012559634/article/details/79496071