标签(空格分隔): LeetCode
题目地址:https://leetcode.com/problems/gas-station/#/description
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.
The solution is guaranteed to be unique.
首先我尝试了暴力解决,时间复杂度O(n^2),可是有个case超时了。这就说明时间复杂度不能太高,应该很可能在O(n)量级,即遍历所有加油站一次就能解决。
然后我就参考了别人的方法。首先明白两点:
所以,在进行遍历时,一方面要记录当前测试的加油站在哪,即start;另一方面要记录在到达start加油站之前缺少的gas之和是多少。
因此只要对所有加油站从标号0开始遍历一次,在遍历时,如果当前加油站不能到达下个加油站,那么start就标记为下个加油站(因为当前加油站对此后所有加油站都不能到);记录从标号0的加油站到标号为start的加油站所有缺少的gas之和need,遍历结束时,判断车厢剩的油是否大于等于从标号0的加油站到start之间缺少的gas之和need。
如果遍历一次结束时油箱剩的gas能大于等于need,说明剩的油可以补充汽车从0跑到start缺少的gas,故返回start;否则无解,返回-1.
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int tank = 0;
int need = 0;
int start = 0;
for (int i = 0; i < gas.length; i++) {
tank += gas[i] - cost[i];
if(tank < 0){
start = i + 1;
need += tank;
tank = 0;
}
}
return tank + need >=0 ? start : -1;
}
}
2017 年 3 月 31 日
手机扫一扫
移动阅读更方便
你可能感兴趣的文章