题解 | #加油站#
加油站
https://www.nowcoder.com/practice/a013a0691a0343aeb262ca1450d2fe4e
- 刚开始尝试第一个开始(下标为0),last标记当前剩余油量
- 当l再次回到0的时候,表明没有方案,返回-1
- 当r == l的时候,表明有方案,返回l
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param gas int整型一维数组
* @param cost int整型一维数组
* @return int整型
*/
public int gasStation (int[] gas, int[] cost) {
int l = 0, r = 1;
int last = gas[0] - cost[0];
while (true) {
while (last < 0 && l != r) {
last = last - gas[l] + cost[l];
l = (l + 1) % cost.length;
if (l == 0) {
return -1;
}
}
last = last + gas[r] - cost[r];
r = (r + 1) % cost.length;
if (r == l) {
return l;
}
}
}
}
查看7道真题和解析