加油站

加油站

加油站

1 题目

在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] ,并且从第 i 个加油站前往第 i+1 个加油站需要消耗汽油 cost[i]

你有一辆油箱容量无限大的汽车,现在要从某一个加油站出发绕环路一周,一开始油箱为空。

求可环绕环路一周时出发的加油站的编号,若不存在环绕一周的方案,则返回-1。

注意事项

数据保证答案唯一。

2 样例

现在有4个加油站,汽油量 gas[i]=[1, 1, 3, 1] ,环路旅行时消耗的汽油量 cost[i]=[2, 2, 1, 1] 。则出发的加油站的编号为2。

3 挑战

O(n)时间和O(1)额外空间

4 思路

public class Solution {
    /**
     * @param gas: an array of integers
     * @param cost: an array of integers
     * @return: an integer
     */
    public int canCompleteCircuit(int[] gas, int[] cost) {
        // write your code here
        int result = 0;
        int totalGas = 0;
        int curGas = 0;
        int remainedGas = 0;
        for (int i = 0; i < gas.length; i++) {
            curGas = gas[i] - cost[i];
            if (remainedGas < 0 && curGas >= 0) {
                result = i;
                remainedGas = 0;
            }

            remainedGas += curGas;
            totalGas += curGas;
        }

        if (totalGas < 0) {
            return -1;
        } else {
            return result;
        }
    }
}

Date: 2017-01-02 12:48

Created: 2017-01-02 周一 13:24

Validate

原文地址:https://www.cnblogs.com/yangwen0228/p/6242336.html