LeetCode每日一题:加油站问题

问题描述

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 costs cost[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.

问题分析

题目的大意是每个加油站有汽油gas[i],从第i个加油站走到第i+1个加油站需要汽油cost[i],所有加油站在一个环上,求我们从哪个加油站出发能够走完一圈,如果不能走完一圈那么返回-1
我们从start=0出发,如果能走过一个加油站,计算他的油的余量是否能走到下一个加油站,如果不能走的话,start++,重复上面的计算

代码实现

public int canCompleteCircuit(int[] gas, int[] cost) {
        int end = gas.length - 1;
        int start = 0;
        int sum = gas[end] - cost[end];
        while (end > start) {
            if (sum >= 0) {
                sum = sum + gas[start] - cost[start];
                start++;
            } else {
                end--;
                sum = sum + gas[end] - cost[end];
            }
        }
        if (sum >= 0) return start;
        else return -1;
    }

你可能感兴趣的:(LeetCode每日一题:加油站问题)