Java for LeetCode 134 Gas Station
2015-06-02 10:44
405 查看
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.
解题思路:
由于答案唯一,所以,只能按照一个方向走(不需要考虑从i+1→i的情况)
考虑到从i出发,到达i+j之后无法前进,那么从i+i出发,最多也只能到达i+j,所以下次循环可以从i+j+1开始,JAVA实现如下:
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.
解题思路:
由于答案唯一,所以,只能按照一个方向走(不需要考虑从i+1→i的情况)
考虑到从i出发,到达i+j之后无法前进,那么从i+i出发,最多也只能到达i+j,所以下次循环可以从i+j+1开始,JAVA实现如下:
public int canCompleteCircuit(int[] gas, int[] cost) { for (int i = 0; i < gas.length; i++) { int sum = gas[i] - cost[i]; int index = i, count = 0; while (sum >= 0) { if (++count == gas.length) return index; int j = ++i % gas.length; sum += gas[j] - cost[j]; } } return -1; }
相关文章推荐
- Java 并发编程框架(一)
- Java 排序算法
- 【转】【java】java中的byte,以及它与int的转化
- Java 并发编程框架(二)
- Java for LeetCode 133 Clone Graph
- Spring Mvc工作原理
- Java 序列化
- java中split方法为何不能用小数点(.)做参数?
- Java邮件工具类
- Spring事务管理—aop:pointcut expression解析
- spring mvc知识点汇总
- java回调简单实现
- JAVA定时执行任务的三种方法
- JAVA持久层框架的概述(ibatis>>mybatis)
- OpenJDK与HashMap
- 【浏览器选择文件夹】springMVC上传篇
- java中 Process的使用
- eclipse怎么设置选中文件编辑的文件时,自动关联选择左侧树里的文件?
- Java中的相对路径与绝对路径
- 解析JDK、J2EE、J2SE、J2ME的区别