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

    题目来源:力扣

  • 相关阅读:
    amq笔记:记一个关于PooledConnectionFactory的问题
    ganglia笔记:rrd数据库
    ganglia笔记:rrds目录
    golang笔记:unsupported driver -> Scan pair: <nil> -> *string
    golang笔记:cookie
    golang笔记:net/smtp
    spring笔记
    Qt坑点汇总
    QT自定义控件系列(二) --- Loading加载动画控件
    Qt自定义控件系列(一) --- 圆形进度条
  • 原文地址:https://www.cnblogs.com/spp666/p/11604567.html
Copyright © 2011-2022 走看看