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.

这题理解题意之后很简单,即要保证gas - cost 的和一直是正的就可以了。 但是要注意这是一个circular。

 1 public class Solution {

 2     public int canCompleteCircuit(int[] gas, int[] cost) {

 3         // Note: The Solution object is instantiated only once and is reused by each test case.

 4         if(gas.length == 0) return -1;

 5         for(int i = 0; i < gas.length; i ++){

 6             gas[i] = gas[i] - cost[i];

 7         }

 8         for(int i = 0; i < gas.length; i ++){

 9             int sum = 0;

10             boolean sig = true;

11             for(int j = i; j < gas.length; j ++){

12                 sum += gas[j];

13                 if(sum < 0){

14                     sig = false;

15                     break;

16                 }

17             }

18             for(int j = 0; j < i; j ++){

19                 sum += gas[j];

20                 if(sum < 0){

21                     sig = false;

22                     break;

23                 }

24             }

25             if(sig == true)return i;

26         }

27         return -1;

28     }

29 }

 

你可能感兴趣的:(IO)