在一条环路上有 N 个加油站,其中第 i 个加油站有汽油gas[i],并且从第i个加油站前往第i+1个加油站需要消耗汽油cost[i]。
你有一辆油箱容量无限大的汽车,现在要从某一个加油站出发绕环路一周,一开始油箱为空。
求可环绕环路一周时出发的加油站的编号,若不存在环绕一周的方案,则返回-1。
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[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.
样例
现在有4个加油站,汽油量gas[i]=[1, 1, 3, 1],环路旅行时消耗的汽油量cost[i]=[2, 2, 1, 1]。则出发的加油站的编号为2。
Example
Given 4 gas stations with gas[i]=[1,1,3,1], and the cost[i]=[2,2,1,1]. The starting gas station’s index is 2.
注意
数据保证答案唯一。
挑战
O(n)时间和O(1)额外空间
Note
The solution is guaranteed to be unique.
Challenge
O(n) time and O(1) extra space
O(n) time and O(1) extra space
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) {
if (gas.length != cost.length) return -1;
int index = 0;
int sumgas = 0;
for(int i = 0; i < gas.length; i++) {
sumgas += gas[i] - cost[i];
if (gas[i] - cost[i] < 0 && sumgas < 0) index = i + 1;
}
if(sumgas < 0) return -1;
return index >= gas.length ? -1 : index;
}
}