Gas Station
来源:互联网 发布:jimmy kimmel知乎 编辑:程序博客网 时间:2024/06/05 14:22
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.
//首先,这个题目要明确如果gas[0] + gas[1] + ... + gas[n] >= cost[0] + cost[1] + .. + cost[n],那么这个题目一定有解。因为,根据条件移项可得://(gas[0] - cost[0]) + (gas[1] - cost[1]) + ... + (gas[n] - cost[n]) >= 0,由于最终结果大于等于零,因此一定可以通过加法交换律,得到一个序列,使得中间结果都为非负public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int start = 0; int currGasRemain = 0; int totalGasRemain = 0; for (int curr = 0; curr < gas.length; curr++) { currGasRemain += gas[curr] - cost[curr]; totalGasRemain += gas[curr] - cost[curr]; if (currGasRemain < 0) { start = curr + 1; // 更新到下一站, 因为cost[curr]表示从curr 站到curr+1 站的花销 currGasRemain = 0; } } return totalGasRemain >= 0 ? start : -1; }}
0 0
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- 【笔记】C与指针 第五章 操作符和表达式
- cocos2d-x 二进制文件的读写
- Unity 3D 琐记
- or1200处理器中的转移类指令介绍
- 网站让浏览器崩溃的原因有哪些
- Gas Station
- 由是否看《小时代》想到的
- 日志传输工具-Flume实现原理及应用
- Keep Walking Ruby !
- visual studio下自动添加注释的插件-VAssistX
- Dynamics CRM ISV文件夹禁用后的解决方案
- servlet 2.5的web.xml
- LA4728 Squares 凸包+旋转卡壳
- JQuery插件第四十个:批量选择检查