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.
用暴力求解方式 两个变量sum和total存储每一站邮箱的剩余量gas[i] - cost[i]
如果sum[i]<0 说明无法走到i+1点 从这个地方开始走并不合适 把sum重置为0
如果sum[i]<0 说明无法走到i+1点 从这个地方开始走并不合适 把sum重置为0
而且不仅这个起点不能作为起点 自起点到sum < 0 的i点的点都不能作为起点 假设能从k (i =>> k=>> j)走,那么i..j < 0,若k..j >=0,说明i..k – 1更是<0,那从k处sum就小于0了,根本轮不到j。那么如果起点都不可以 中间的点就都不可以
因为如果当前次不行就要从i+1开始走 走到i= lengh时候toal记录了从头到尾的gas-cost 所以如果total为+ 那么久可以走完 但是total为- 就不可以
时间O(n) 空间 O(1)
时间O(n) 空间 O(1)
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
if (gas == null || cost == null || gas.length == 0 || cost.length == 0) {
return -1;
}
int sum = 0;
int total = 0;
int index = 0;
for (int i = 0; i < gas.length; i++) {
sum += gas[i] - cost[i];
total += gas[i] - cost[i];
if (sum < 0) {
sum = 0;
index = i + 1;
}
}
if (total < 0) {
return -1;
} else {
return index;
}
}
}
没有评论:
发表评论