我是靠谱客的博主 粗心牛排,这篇文章主要介绍【leetcode/python/134】Gas Station,现在分享给大家,希望可以做个参考。

题目

https://leetcode.com/problems/gas-station/

题目太长了,还是直接贴链接吧~
题目很长,但是理解起来还是比较容易的:

在一条环形的路上有N个加油站,每个加油站里有gas[i]的汽油,从第i个加油站到第i+1个加油站需要花费cost[i]的汽油。假设汽车的油箱可以装无数的汽油,判断一辆没有油的汽车是否可以从其中的某一个加油站出发并行驶一圈后返回该加油站。如果可以的话,返回起始加油站的下标,否则返回-1。

实现代码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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 length = len(gas) startIndex,diff = 0,0 for i in range(length): if gas[i] + diff < cost[i]: startIndex = i + 1 diff = 0 else: diff += gas[i]- cost[i] return startIndex

最后

以上就是粗心牛排最近收集整理的关于【leetcode/python/134】Gas Station的全部内容,更多相关【leetcode/python/134】Gas内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(64)

评论列表共有 0 条评论

立即
投稿
返回
顶部