【題目】
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.
【題意】
環形路線上有N個加油站,每個加油站有汽油gas[i],從每個加油站到下一站消耗汽油cost[i],問從哪個加油站出發能夠回到起始點,如果都不能則返回-1(注意,解是唯一的)。
【Java代碼】(O(n^2))
- public class Solution {
- public int canCompleteCircuit(int[] gas, int[] cost) {
- //依次從每一個加油站出發
- for (int i = 0; i < gas.length; i++) {
- int j = i;
- int curgas = gas[j];
- while (curgas >= cost[j]) { //如果當前的汽油量能夠到達下一站
- curgas -= cost[j]; //減去本次的消耗
- j = (j + 1) % gas.length; //到達下一站
- if (j == i) return i; //如果回到了起始站,那麼旅行成功
- curgas += gas[j]; //到下一站後重新加油,繼續前進
- }
- }
- return -1;
- }
- }
【Java代碼】(O(n))
- public class Solution {
- public int canCompleteCircuit(int[] gas, int[] cost) {
- int sum = 0;
- int total = 0;
- int j = -1;
- for (int i = 0; i < gas.length; i++) {
- sum += gas[i] - cost[i];
- total += gas[i] - cost[i];
- if(sum < 0) { //之前的油量不夠到達當前加油站
- j = i;
- sum = 0;
- }
- }
- if (total < 0) return -1; //所有加油站的油量都不夠整個路程的消耗
- else return j + 1;
- }
- }