<span style= "font-family: ' Helvetica Neue ', Helvetica, Arial, Sans-serif; Background-color:rgb (255, 255, 255); " ></span>
There was N gas stations along a circular route, where the amount of gas at Station I was gas[i]
.
You had a car with an unlimited gas tank and it costs of gas to travel from station cost[i]
I to its next station (i+ 1). You begin the journey with a 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.
I started thinking a bit simple: 1) If the gas sum is less than the sum of cost, then certainly not, but if gas>=cost, then you can find the way out
2) If it is greater than that, then we will not find the largest gas supply station is good? The biggest will not, the other must not
So I wrote a paragraph like:
public int cancompletecircuit (int[] gas, int[] cost) {Int. ans=-1;//If gas is less than cost, it is certainly not, otherwise it is sure to be able if (stats (gas) <stats ( Cost) {return ans;} Ans = maxnum (gas); return ans;} See how much gas or costpublic static int stats (int[] input) {int res=0;for (int i=0;i<input.length;i++) {res+=input[i ];} return res;} Look at the most of the subscript public in this array public static int maxnum (int[] input) {int max=0;if (input==null| | input.length==0) return-1;for (int i=0;i<input.length;i++) {if (Input[i]>max) max = i;} return Max;}
Later found not, because did not consider this situation: Although the Start is 5 (the most), but it will go the following cost is also 5, followed by gas than the cost of more then the No. So we have to change a way of thinking, we put together a circle of gas-cost, from a certain point will be "profit", from the gas will not be less than cost, the turning point is actually we want to find the starting point, because from that point will never "make ends meet". So we're going to record the last sum<0 point, and then put this point +1, and finally, because it's a circle, so don't forget to be (index+)% total
public int cancompletecircuit (int[] gas, int[] cost) {Int. Ans=-1;int sum=0;int total=0;if (stats (gas) <stats (cost)) return ans;for (int i=0;i<gas.length;i++) {sum + = Gas[i]-cost[i];total + gas[i]-cost[i];if (sum<0) {ans=i;sum=0;}} if (total<0) Return-1;else return (ans+1)%gas.length;} See how much gas or costpublic static int stats (int[] input) {int res=0;for (int i=0;i<input.length;i++) {res+=input[i ];} return res;}
Finally ran through the ~
"Leetcode" gas station