leetcode-134. Gas Station
来源:互联网 发布:淘宝网天猫商城家俱 编辑:程序博客网 时间:2024/05/17 22: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.
题意解析:
题目大概就是说有一个环形的路线,路线上有很多分布的加油站,每个加油站的油量是```gas[i]```,然后你开一辆车,从某一个加油站出发,看看能否绕一圈,从一个加油站到下一个加油站需要的油量是‘’‘cost[i]’‘’。如果可以的话,就返回出发的那个加油站的下标```i```,不行的话就返回-1。
答案假定是唯一的。
首先按照正常思路可以想到一个暴力解决的方法,就是去循环遍历每个结点,试着环绕一圈,代码如下:
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { for(int i = 0; i < gas.length; i++){ int currentGas = gas[i]; int j = i; while(currentGas >= cost[j]){ //能够到达下一站 currentGas -= cost[j]; j = (j+1) % gas.length; if(j == i){ return i; } currentGas += gas[j]; } } return -1; }}上述代码复杂度O(n^2),思路简单清晰,然而,难度是Medium的题目怎么可能就这么解决呢?
提交代码,超时了。很尴尬,只能想一些巧妙的方法。
这里应该这么想,想要完成全程其实只要满足两个条件即可,第一个是,所有的gas和大于cost和。第二个就是,当前油量可以到达下一站。第二个条件的实现有点抽象,我会在代码里解释,并在后面给出更详细的说明,代码如下:
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int sum = 0; int total = 0; int j = 0; for(int i = 0; i < gas.length; i++){ sum += gas[i] - cost[i]; total += gas[i] - cost[i]; if(sum < 0){ //说明此时汽车无法到达下一站,所以之前所有的i包括当前i都不能作为起点。起点只可能是后面的某个值 j = i + 1; sum = 0; } } if(total >= 0){ return j; }else{ return -1; } }}这个算法用total来表示总油量是足够支持到下一站的,sum则表示能不能到达下一站,可以证明:如果```gas[i] >= cost[i]```,则可以出发,并且带有储存油量,如果一直保持了```gas[i] >= cost[i]```这个条件,则说明储存的油量是在不断增加的,所以如果某一次出现```currestGas + gas[i] < cost[i]```,不仅说明不能从这一站出发,还说明了不能从之前的任一站出发。所以就先假定下一站是可以出发的。
代码复杂度是O(n),运行时间也只有1ms,已经是最优算法了,至于前面的0ms,大概是以前的数据或者是在服务器性能极好的时候进行了提交,导致时间短到离谱。
- [LeetCode]134.Gas Station
- LeetCode 134. Gas Station
- [Leetcode] 134. Gas Station
- [leetcode] 134. Gas Station
- Leetcode-134.Gas Station
- 134. Gas Station LeetCode
- Leetcode 134. Gas Station
- [LeetCode]134. Gas Station
- LeetCode 134. Gas Station
- leetcode 134. Gas Station
- LeetCode *** 134. Gas Station
- LeetCode 134. Gas Station
- 【LeetCode】134. Gas Station
- LeetCode - 134. Gas Station
- LeetCode 134. Gas Station
- LeetCode 134. Gas Station
- [leetcode] 134. Gas Station
- leetcode-134. Gas Station
- 在Service或者BroadCastReceiver中弹出dialog
- caffe全连接层原理解读
- Cannot forward after response has been committed 问题原因。
- 我向未来又踏进了一步
- Java基础-IO学习之字节流
- leetcode-134. Gas Station
- JAVA的一丢丢基础
- HTTP 协议详解(超级经典)
- HDU1907 John Nim游戏
- bzoj 3065 带插入区间K小值 重量平衡treap套主席树
- VS2008LINK : fatal error LNK1000: Internal error during IncrBuildImage
- 八大内部排序--快速排序
- 高效学习--BOST学习技巧组合
- 技术人员的未来:做技术还是做管理?