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;
}

最新文章

  1. iOS开发——项目实战总结&amp;关于随机量
  2. 在linux下挂载、卸载U盘
  3. hdu4763 KMP
  4. Datagrid扩展方法InitEditGrid{支持单元格编辑}
  5. ImageSource使用心得(转)
  6. 【bzoj3110】[Zjoi2013]K大数查询
  7. C#程序设计六大原则记录
  8. 理解jQuery的$.extend与$.fn.extend
  9. CSS 模块的侦测
  10. 8:String类
  11. enum使用方法
  12. uuid唯一吗
  13. 在Node中使用ES6语法
  14. 内核调试神器SystemTap 转摘
  15. 10个好用的JQuery代码片段收集
  16. css中奇怪的地方
  17. javascript编译与运行机理(1)--
  18. [svc]linux测速软件speedtest-cli
  19. 上下文管理器 contextlib
  20. smartJS 0.1 API 讲解 - Trigger

热门文章

  1. 设计模式UML图
  2. 移动页面缩放方法之(二)控制HTML
  3. 【转】数据库分页Java实现
  4. Linq101-QueryExecution
  5. 注册表修改IP地址和DNS等信息
  6. C#word(2007)操作类--新建文档、添加页眉页脚、设置格式、添加文本和超链接、添加图片、表格处理、文档格式转化
  7. drop table xx purge
  8. CSS 布局Float 【2】
  9. [转载]C++中 引用&amp;与取地址&amp;的区别
  10. 模仿qq音乐播放字母效果