题目:Gas Station
难度:MEDIUM
问题描述:
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.
解题思路:
1.如果gas和大于cost和,必定有解。
2.从i开始,如果到k时,gas和小于cost和,那么解必定不在I和k之间(包含两端)
有了上面两点,题目就很容易解了,代码如下:
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int total = 0;
int len = gas.length;
for(int i=0;i<len;i++){
total +=gas[i]-cost[i];
}
if(total<0) return -1;
for(int i=0;i<len;i++){
int rest=0;
int index=i;
int count=0;
while(!(rest<0)&&count<len){
rest +=gas[index]-cost[index];
if(rest<0){
break;
}
index++;
count++;
if(index==len) index=0;
}
if(count==len) return index;
else i=index;
}
return -1;
}
}