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

    题目来源:力扣

  • 相关阅读:
    【java虚拟机】垃圾回收机制详解
    【java虚拟机】分代垃圾回收策略的基础概念
    【java虚拟机】内存分配与回收策略
    【java虚拟机】jvm内存模型
    【转】新说Mysql事务隔离级别
    【转】互联网项目中mysql应该选什么事务隔离级别
    有关PHP的字符串知识
    php的查询数据
    php练习题:投票
    php的数据访问
  • 原文地址:https://www.cnblogs.com/spp666/p/11604567.html
Copyright © 2011-2022 走看看