Gas Station——LeetCode
2024-10-15 22:47:27
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.
题意大概是:有N个加油站围成一个圈,每个加油站的油量是gas[i],从第i个加油站开到第i+1个加油站需要耗费cost[i]油量,问是否有一个解使得从某个加油站开始跑一圈,有的话返回开始跑的加油站的index。
我的做法就是从0开始遍历,sum+=gas[i]-cost[i],一旦sum<0了,说明从当前到0的所有点都不可能了,然后从下一个开始,一旦跑完一圈发现sum都不小于0,那么就可以返回当前的index了,否则全部遍历一遍没有解就返回-1。
Talk is cheap>>
public int canCompleteCircuit(int[] gas, int[] cost) {
int res;
for (int i = 0; i < gas.length; i++) {
res = gas[i] - cost[i];
if (res >= 0) {
int pos = i;
for (int j = pos + 1; j < gas.length + pos; j++) {
int index = j % gas.length;
res += gas[index] - cost[index];
if (res < 0) {
pos = -1;
i = j;
break;
}
}
if (pos >= 0)
return pos;
}
}
return -1;
}
最新文章
- iOS开发——项目实战总结&;关于随机量
- 在linux下挂载、卸载U盘
- hdu4763 KMP
- Datagrid扩展方法InitEditGrid{支持单元格编辑}
- ImageSource使用心得(转)
- 【bzoj3110】[Zjoi2013]K大数查询
- C#程序设计六大原则记录
- 理解jQuery的$.extend与$.fn.extend
- CSS 模块的侦测
- 8:String类
- enum使用方法
- uuid唯一吗
- 在Node中使用ES6语法
- 内核调试神器SystemTap 转摘
- 10个好用的JQuery代码片段收集
- css中奇怪的地方
- javascript编译与运行机理(1)--
- [svc]linux测速软件speedtest-cli
- 上下文管理器 contextlib
- smartJS 0.1 API 讲解 - Trigger