[LeetCode]题解(python):134-Gas Station
2016-04-05 14:35
579 查看
[b]题目来源:[/b]
https://leetcode.com/problems/gas-station/
[b]题意分析:[/b]
在一个圈子路线里面有N个汽油站,i站的汽油有gas[i]汽油。现在有一辆无限容量的车,它从i站开到(i+1)需要耗费cost[i]汽油。如果这辆车可以走完这个圈,那么返回这个车的起点,否者返回-1.
[b]题目思路:[/b]
不难发现,如果gas的总和大于或等于cost的总和,必然存在一种路线使得走完整个圈子。那么只要找到一个起点i,从这个起点出发的所有gas的和总比cost的和大就可以了。
[b]代码(python):[/b]
View Code
https://leetcode.com/problems/gas-station/
[b]题意分析:[/b]
在一个圈子路线里面有N个汽油站,i站的汽油有gas[i]汽油。现在有一辆无限容量的车,它从i站开到(i+1)需要耗费cost[i]汽油。如果这辆车可以走完这个圈,那么返回这个车的起点,否者返回-1.
[b]题目思路:[/b]
不难发现,如果gas的总和大于或等于cost的总和,必然存在一种路线使得走完整个圈子。那么只要找到一个起点i,从这个起点出发的所有gas的和总比cost的和大就可以了。
[b]代码(python):[/b]
class Solution(object): def canCompleteCircuit(self, gas, cost): """ :type gas: List[int] :type cost: List[int] :rtype: int """ begin,subsum,sum,i = 0,0,0,0 while i < len(gas): sum += gas[i] - cost[i] subsum += gas[i] - cost[i] if subsum < 0: subsum,begin = 0,i + 1 i += 1 if sum < 0: return -1 else: return begin
View Code
相关文章推荐
- Python:函数式编程与函数
- python+selenium+scrapy搭建简单爬虫
- Python:类与结构体
- uva352 The Seasonal War-python
- python学习过程-集合和for循环
- 利用python下载网页到本地(python3)
- [LeetCode]题解(python):133-Clone Graph
- K近邻分类算法实现 in Python
- ArcMap中用python的split方法提取字段的值
- Python:random模块
- python小项目1
- python内建函数sorted方法概述
- python内建函数sorted方法概述
- Ilya and Escalator-python
- Python:正则表达式模块
- python进阶
- python路径相关的函数os.listdir(dirname):列出dirname下的目录和文件
- python os.path模块常用方法详解
- python实现并行爬虫
- python多线程threading