134. Gas Station
来源:互联网 发布:优惠券由来 知乎 编辑:程序博客网 时间:2024/06/15 02:48
134. Gas Station
题目
在一个环形路线上有N个加油站,在加油站的汽油量为 gas[i]。
你有一辆可以装无限量汽油的小车,从加油站[i]到它的下一站[i+1]需要消耗 cost[i] 的汽油。从某一个加油站以空邮箱开始你的旅程。
如果你可以绕着环形路线行驶一圈,返回开始加油站的索引,否则返回-1。
注意:答案是唯一的。
代码块
class Solution { public static int canCompleteCircuit(int[] gas, int[] cost) { int start = 0; int curGas = 0;//初始化 int sum = 0; for(int i = 0; i < gas.length; i++){ curGas += gas[i] - cost[i];//+= sum += gas[i] - cost[i]; if(curGas < 0){ //当前油量不够行驶到下一站。 // start++; start = i+1; curGas = 0; } } if(sum < 0){ // 总的油量不够行驶一圈。 return -1; }else{ return start; } } public static void main(String[] args) { int[] gas = {1,2,4}; int[] cost = {2,1,3}; System.out.println(canCompleteCircuit(gas, cost)); }}
代码分析
这道题一开始没看懂题意,然后就去搜代码,以及解析,debug后才能基本理解。
问题一:没有“+=”,就不能做到累加。
问题二:没有初始化变量curGas和sum,就去“+=”;所以报错。
问题三:不知道循环体的范围。把所有都写到了for循环体内。理解不到位。
阅读全文
0 0
- [LeetCode]134.Gas Station
- LeetCode 134. Gas Station
- [Leetcode] 134. Gas Station
- 134. Gas Station
- [leetcode] 134. Gas Station
- Leetcode-134.Gas Station
- 134. Gas Station LeetCode
- 134. Gas Station
- Leetcode 134. Gas Station
- 134. Gas Station
- 134. Gas Station
- [LeetCode]134. Gas Station
- LeetCode 134. Gas Station
- leetcode 134. Gas Station
- LeetCode *** 134. Gas Station
- 134. Gas Station
- LeetCode 134. Gas Station
- 【LeetCode】134. Gas Station
- Android基础入门教程——2.2.5 GridLayout(网格布局)
- SQLServer中的日期函数
- 文章标题
- Densely Connected Convolutional Networks翻译
- 使用Jenkins进行持续集成
- 134. Gas Station
- linux下测试写满cpu
- opencv for python (7) 计算中值滤波函数程序的运行时间,及简要解释中值滤波函数
- 想下代码,却没有C币.....
- 十三、c++模板基础
- 最详细的Vuex教程
- 简单的nginx服务器vhost配置
- 深入理解PHP原理之函数(Introspecting PHP Function)
- linux ttyS设备的close