Link: https://oj.leetcode.com/problems/gas-station/
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.
Note:
The solution is guaranteed to be unique.
我的思路:需要两个条件:
1 加油站油的总量不小于耗油总量:sum(gas[i]) >= sum(cost[i])
2 从加油站i 到i+1: //这部分不会写。如果start != 0, 怎样遍历循环数组? i.e. start = 2, gas[0], gas[1]如何访问?
如果i == start 是起始点:gas[i] - cost[i] >=0
如果不是:gas[i]-cost[i]+gas[i+1] >= cost[i+1]
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int sumGas = 0;
int sumCost = 0;
for(int i = 0; i < gas.length; i++){
sumGas += gas[i];
sumCost += cost[i];
}
if(sumGas < sumCost) return -1;
int i = 0;
for(int i = 0; )
}
}
思路基本正确,但还不够清楚。再做。
正确思路:设两个量,一个是当前序列的累计油量sum,一个是总的累积油量total。有解的充分必要条件是:sum>=0 && total>=0
证明见:http://blog.csdn.net/linhuanmars/article/details/22706553 (没有完全看懂)
Time: O(n), Space: O(1)
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int sum = 0;
int total = 0;
int j = 0;//start station index
for(int i = 0; i < gas.length; i++){
int diff = gas[i] - cost[i];
sum += diff;
if(sum < 0){//cannot reach gas station i+1, start from next station
j = i+1;
sum = 0;
}
total += diff;
}
return total >=0 ? j : -1;
}
}