两种解法
1. 两层遍历,直观取得结果 --- 时间复杂度高 ,不过, 但如果要求返回所有满足的位置,可以用这种方法
2. 题目只要求返回一个结果即可,那么有以下两个条件,即满足题意
a. ∑gas[i] >= ∑cost[i]
b. 从cost[i]-gas[i]的负数最小的地方,往后找到第一个cost[i]-gas[i]>0的index,则此位置即满足要求
第一种解法,(time limit exceeded)
public int canCompleteCircuitFailed(int[] gas, int[] cost) {
if(gas == null || gas.length==0){
return -1;
}
for(int i=0; i<gas.length; i++){
if(cost[i]>gas[i]){
continue;
}
int totalGas =0 ;
int totalCost =0 ;
int j=i;
boolean circuitFlag = true;
while (true){
if(j == i && circuitFlag){
circuitFlag = false;
}else if(j==i && !circuitFlag ){
return i;
}
totalCost += cost[j];
totalGas += gas[j];
if(totalCost > totalGas){
break;
}
if((j+1)==gas.length){
j = 0;
}else {
j++;
}
}
continue;
}
return -1;
}
第二种
public int canCompleteCircuit(int[] gas, int[] cost) {
int gasCostMin = 0;
int gasMinIndex = -1;
int totalGas = 0;
int totalCost = 0;
for(int i=0; i<gas.length; i++){
if((gas[i]-cost[i]) < gasCostMin){
gasCostMin = gas[i]-cost[i];
gasMinIndex = i;
}
totalCost += cost[i];
totalGas += gas[i];
}
if(totalGas >= totalCost){
if(gasMinIndex == -1){
return 0;
}
int j = gasMinIndex;
while (true){
if(gas[j]-cost[j]>0){
return j;
}
j++;
if(j==gas.length){
j=0;
}
}
}
return -1;
}