[LeetCode]Gas Station
来源:互联网 发布:vb脚本怎么运行 编辑:程序博客网 时间:2024/06/06 00:44
题目分析
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, otherwise return -1.
Note:
The solution is guaranteed to be unique.
解题思路
由上图我们来进行分析,我们定义reminder表示从一个站点到下一个站点时剩余的油量,初始为0。
如果要满足题目要求,则应需要满足以下条件:
- 对于每一段路程,reminder>=0;
- 对于每一段路程,remainder + gas[j % len] >= cost[j % len];
- 若想完成一圈,则应从起始站点i环绕一圈再走到i,且满足上述的两点;
这时我们很容想到通过循环n次,并在每次循环中开始遍历,看能否满足上述3点。这样想是非常正确的,但是你是否觉得有点问题?
对,这样做会超时,为什么呢?
我们来考虑,如果从0到i走不通,在i处中断,那么从1、2、3、i-1到i能否走通呢?答案是否定的,仔细想明白这一点我们就可以简化循环,节省时间。具体请看代码。
代码
public int canCompleteCircuit(int[] gas, int[] cost) { int len = gas.length;int remainder = 0;for (int i = 0; i < len; i++) {int j = i;while (j != len + i) {if (remainder >= 0 && remainder + gas[j % len] >= cost[j % len]) {remainder = remainder + gas[j % len] - cost[j % len];j++;} else { i = j;break;}}if (j == len + i) {return i;}}return -1; }
0 0
- LeetCode:Gas Station
- [LeetCode] Gas Station
- [leetcode]Gas Station
- Leetcode: Gas Station
- LeetCode:Gas Station
- [LeetCode] Gas Station
- leetcode Gas Station
- [LeetCode]Gas Station
- LeetCode 之 Gas Station
- leetcode Gas Station
- 【Leetcode】Gas Station
- LeetCode | Gas Station
- LeetCode之Gas Station
- Leetcode: Gas Station
- LeetCode OJ:Gas Station
- [LeetCode]134.Gas Station
- [Leetcode] Gas Station (Java)
- gas station leetcode
- iOS的基本的设计模式
- 基于NFC技术的移动支付终端
- HttpClient 教程 (四)
- Linux设备模型之input子系统详解
- Hibernate实战_笔记17(持久化实体类)
- [LeetCode]Gas Station
- 使用 Netbeans 创建 Symfony2 项目
- Illustrated C#2012--第一章节--C#和.NET Framework
- hadoop自学轨迹-hadoop2.2.0单NameNode安装
- 参数类型不同的函数重载(C++)
- ACM日历题新版(界面修改+国际节日)
- HttpClient 教程 (五)
- Codeforces 401D Roman and Numbers(记忆化搜索)
- HDOJ 1874 畅通工程续(Dijkstra+Floyed+SPFA)