题目描述
There are N gas stations along a circular route, where the amount of gas at station i isgas[i].
You have a car with an unlimited gas tank and it costscost[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,注定是断的。
import java.util.ArrayList;
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
if(gas.length==0||gas==null)return -1;
if(gas.length==1) {
if(gas[0]<cost[0])return -1;
else return 0;
}
int remaingas = gas[0];//地点0车上剩余的油
/**
* index,index:无法去往下一地点的该地下标,当前剩余的油
*/
ArrayList<Integer> firstindex = new ArrayList<Integer>();
ArrayList<Integer> remain = new ArrayList<Integer>();
for (int i = 0; i < gas.length-1; i++) {
if(remaingas>=cost[i]) {
remaingas=remaingas-cost[i]+gas[i+1];
}else {
firstindex.add(i);
remain.add(remaingas);
remaingas= gas[i+1];
}
}
//判断最后一位能不能到首位
if(remaingas<cost[gas.length-1]) {
//不能
firstindex.add(gas.length-1);
remain.add(remaingas);
return -1;
}else {
//能
//判断多余的油能不能让走不过的路走过
remaingas = remaingas - cost[gas.length-1];
for (int j = 0; j < firstindex.size(); j++) {
int i = firstindex.get(j);
remaingas = remain.get(j)+remaingas;
if(remaingas>=cost[j]) {
remaingas = remaingas - cost[j];
}else {
return -1;
}
}
}
//能形成一个圆就找到起始地点,
//起始地点是firstindex的最后一个值的下一个地点,如果最后一个值是gas。length-1,那么下一个就是0;
return firstindex.get(firstindex.size()-1)==gas.length-1?0:firstindex.get(firstindex.size()-1)+1;
}
}
别人写的:
这个解法是很精辟的,当油不够时,start就往前退一步,是为了加油。而end++是为了消耗油。
这种平衡的写法,很厉害。
高手。
从start出发, 如果油量足够, 可以一直向后走 end++; 油量不够的时候,
start向后退 最终 start == end的时候,如果有解一定是当前 start所在位置
class Solution {
public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int start = gas.size() - 1;
int end = 0;
int sum = gas[start] - cost[start];
while(start > end){
if(sum >= 0){
sum += gas[end] - cost[end];
++end;
}else{
--start;
sum += gas[start] - cost[start];
}
}
return sum >=0 ? start : -1;
}
};