加油站
问题描述
在一条环路上有 N 个加油站,其中第 i 个加油站有汽油gas[i],并且从第_i_个加油站前往第_i_+1个加油站需要消耗汽油cost[i]。
你有一辆油箱容量无限大的汽车,现在要从某一个加油站出发绕环路一周,一开始油箱为空。
求可环绕环路一周时出发的加油站的编号,若不存在环绕一周的方案,则返回-1。
!数据保证答案唯一!
样例
样例 1:
输入:gas[i]=[1,1,3,1],cost[i]=[2,2,1,1]
输出:2
样例2 :
输入:gas[i]=[1,1,3,1],cost[i]=[2,2,10,1]
输出:-1
大致思路
从头遍历一遍数组,用total记录从头开始的油量情况,用cur记录当前有量,
如果cur小于0,则把cur置0,pos则设置为下一个点,遍历结束后,
判断total是否大于等于0,小于0则返回-1,否则返回pos
Java代码
public class Solution {
/**
* @param gas: An array of integers
* @param cost: An array of integers
* @return: An integer
*/
public int canCompleteCircuit(int[] gas, int[] cost) {
// write your code here
int n = gas.length;
int total = 0, cur = 0, pos = 0;
for (int i = 0; i < n; i++) {
total += gas[i] - cost[i];
cur += gas[i] - cost[i];
if (cur < 0) {
cur = 0;
pos = i+1;
}
}
return total >= 0 ? pos : -1;
}
}