Gas Station 解答
2015-10-07 09:45
295 查看
Problem
There are N gas stations along a circular route, where the amount of gas at station i isgas[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.
Solution
Key to the solution is a conclusion:If sum of gas >= sum of costs, then there must exists one or more solution.
If sum of gas < sum of costs, then there is no solution.
So we can use method of exclusion here.
We need also note here that if A can not reach C in a the sequence of A-->B-->C, then B can not make it either.
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { if (gas == null || cost == null) return -1; if (gas.length != cost.length) return -1; int start = 0; int sumRemaining = 0; int totalRemaining = 0; for (int i = 0; i < gas.length; i++) { int tmp = gas[i] - cost[i]; if (sumRemaining >= 0) { sumRemaining += tmp; } else { start = i; sumRemaining = tmp; } totalRemaining += tmp; } if (totalRemaining < 0) return -1; return start; } }
相关文章推荐
- 缓冲区溢出漏洞攻击演示实验
- Mybatis整合Spring
- 详细解读Java编程中面向字符的输入流
- 树——线段树区间修改
- MySQL
- HTML-<a>标签添加下划线
- Mybatis typealiaspackage 通配符扫描方法
- Spring的OpenEntityManagerInViewFilter
- 如何捕获 Linux 图形化登录界面的截图
- 某鸟神总结的知识点(5)
- Hibernate拦截器
- 基于HCE移动支付研究报告
- 分子生物学上的生物定义整理
- 稳定的匹配算法–Gale-Shapley
- Spring antmatcher 使用路径通配符加载Resource,
- 回忆当初写过的代码
- python文本处理
- LFS 中文版手册发布:打造自己的 Linux 发行版
- 乌班图使用
- Thinkphp快速载入文本编辑器