LeetCode134加油站
程序员文章站
2024-03-11 11:28:37
...
在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。
你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。
如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。
说明:
如果题目有解,该答案即为唯一答案。
输入数组均为非空数组,且长度相同。
输入数组中的元素均为非负数。
输入:
gas = [1,2,3,4,5]
cost = [3,4,5,1,2]
输出: 3
解释:
从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油
开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油
开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油
开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油
开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油
开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。
因此,3 可为起始索引
思路一,每次遇到gas[i]>cost[i]的时候,就开始遍历。看是否能够到达终点。怎么判断到达终点,用一个变量值count,初始值为0,每次递归+1,直到gas.length即可
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
for(int i =0;i<gas.length;i++){
if(gas[i]>=cost[i]){
if(isTrue(gas,cost,i,0,0)==1){
return i;
}
}
}
return -1;
}
public int isTrue(int[] gas,int[] cost,int key,int val,int count){
if(count == gas.length){
return 1;
}
if(val + gas[key] - cost[key]<0){
return 0;
}
return isTrue(gas,cost,(key+1)%gas.length,val + gas[key] - cost[key],count+1);
}
}
怎么优化
如果从0开始遍历,某个值gas[i]-cost[i]>0,但是不能够到达终点,所以中间的位置不用遍历,直接跳过即可。
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.length;
int i = 0;
while (i < n) {
int sumOfGas = 0, sumOfCost = 0;
int cnt = 0;
while (cnt < n) {
int j = (i + cnt) % n;
sumOfGas += gas[j];
sumOfCost += cost[j];
if (sumOfCost > sumOfGas) {
break;
}
cnt++;
}
if (cnt == n) {
return i;
} else {
i = i + cnt + 1;
}
}
return -1;
}
}
折线图方法。其实就是折线图上下平移
gas[i]-cost[i]每次相加,到达最小值,(因为我们不需要,前面的都是负数,而且负数越来越小。为什么要加上,对吧,仔细想一想就行了)就从下一个位置开始走。当然,循环之后如果sum总和<0就输出-1;
public int canCompleteCircuit(int[] gas, int[] cost) {
int len = gas.length;
int spare = 0;
int minSpare = Integer.MAX_VALUE;
int minIndex = 0;
for (int i = 0; i < len; i++) {
spare += gas[i] - cost[i];
if (spare < minSpare) {
minSpare = spare;
minIndex = i;
}
}
return spare < 0 ? -1 : (minIndex + 1) % len;
}