[LeetCode] [Java] Gas Station
Question:
There are N gas stations along a circular route, where the amount of gas at station I isgas[i].
You have a car with an unlimited gas tank and it costscost[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.
Question:
There are N gas stations in a circular path, and the number of gasoline on location I isgas[i].
You have a car, the fuel tank of this car is infinite capacity, it from the gas station I to the gas station (I + 1) need to consume the number of gasoline cost [I]. when you start this journey, your initial state is one of the gas stations, and the fuel tank is empty.
If the entire Circular Road is completed at one time, the serial number of your actual gas station is returned. If the whole road cannot be completed,-1 is returned.
Note:
The solution guarantee is unique.
Algorithm analysis:
The brute-force solution is a good idea, but it times out. That is, from the beginning of each station, it has been walking around, accumulating the amount of fuel in the process, to see if it has been negative, if there is a failure, from the next station to another circle; if there is no negative result, the site can be used as the starting point and succeeded. We can see that we need to scan a circle each time and perform a scan for each site. Therefore, the time complexity is O (n2 ).
An improved algorithm is provided. The main idea of the method is to divide this circle into negative sequences and a positive sequence (if any ). Starting from any station, we can accumulate the remaining amount of fuel. If there is negative, the sequence ends, and a new one is started, it proves that the starting point of the old sequence cannot be used as the starting point, because there will be negative oil, you cannot proceed. In addition, the starting point of the negative sequence cannot be used as the starting point, and any point in the negative sequence cannot be used as the starting point. The proof is not provided. If you are interested, refer to the above blog.
Algorithm Description: If sum is less than 0 when I = k, it means that the car cannot reach the k gas station. It must start from the next gas station and determine whether the car can circle.
AC code:
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; // The total net capacity reached the current gas station int total = 0; // The total capacity of the entire completed cycle int pointer = 0; // defines the starting point for (int I = 0; I
= 0? Pointer:-1 ;}}