zoukankan      html  css  js  c++  java
  • 力扣——gas station (加油站) python实现

    题目描述:

    中文:

    在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。

    你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。

    如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。

    说明:

    如果题目有解,该答案即为唯一答案。
    输入数组均为非空数组,且长度相同。
    输入数组中的元素均为非负数。

    英文:

    There are N gas stations along a circular route, where the amount of gas at station i is gas[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 in the clockwise direction, otherwise return -1.

    Note:

    If there exists a solution, it is guaranteed to be unique.
    Both input arrays are non-empty and have the same length.
    Each element in the input arrays is a non-negative integer.

    class Solution(object):
        def canCompleteCircuit(self, gas, cost):
            """
            :type gas: List[int]
            :type cost: List[int]
            :rtype: int
            """
            if sum(gas) < sum(cost): return -1
            n = len(gas)
            diff = 0
            stationIndex = 0
            for i in range(n):
                if gas[i]+diff < cost[i]: stationIndex = i+1; diff = 0
                else: diff += gas[i]-cost[i]
            return stationIndex

    题目来源:力扣

  • 相关阅读:
    iOS-延迟操作方法总结
    IOS开发调整UILabel的行间距
    day16 包和random模块 time模块 进度条
    day15 软件开发规范 日志输出和序列化反序列化
    day14 列表生成式 生成器表达式 模块
    day13 函数三元表达式,递归
    day11 装饰器
    day10作用域与闭包
    day9 函数的形参和实参
    day8 函数
  • 原文地址:https://www.cnblogs.com/spp666/p/11604567.html
Copyright © 2011-2022 走看看