187. 加油站

187. 加油站

中文English

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

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

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

样例

样例 1:

输入:gas[i]=[1,1,3,1],cost[i]=[2,2,1,1]
输出:2

样例 2:

输入:gas[i]=[1,1,3,1],cost[i]=[2,2,10,1]
输出:-1

挑战

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

注意事项

数据保证答案唯一。

输入测试数据 (每行一个参数)如何理解测试数据?
class Solution:
    """
    @param gas: An array of integers
    @param cost: An array of integers
    @return: An integer
    """
    '''
    大致思路:
    1.给出total 汽油量,如果汽油量小于0的话,则当前位置index+1,并且重置汽油量.直到最后一直符合的即跳出
    '''
    def canCompleteCircuit(self, gas, cost):
        if sum(gas) < sum(cost):
            return -1
        
        total = 0
        j = 0 
        for i in range(len(gas)):
            total = total + gas[i] - cost[i]
            if total < 0:
                total = 0
                j = i + 1
        return j
原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12865975.html