LeetCode#134. Gas Station

  • Question: A circular gas station, the i-th station stores gasoline gas[i], and it takes gasoline cost[i] to go from the i-th gas station to the i+1-th gas station. Find a starting position from the circular gas station such that Can complete the entire circular stroke. Returns -1 if no such path exists.
  • Ideas:

    1.如果总共的汽油>=总共的花费,说明一个存在一条满足条件的路径。
    
    2.默认设置起点为第0个位置,如果起点能够到达第i个点,则到达第i个点时汽油剩余量>=0,否则起点重新设置为i+1
    
  • Difficulty: Medium
  • Code:
public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        if(gas == null || gas.length == 0 || cost == null || cost.length == 0){
            return -1;
        }
        int tank = 0;
        int sumGas = 0;
        int sumCost = 0;
        int start = 0;
        for(int i = 0; i < gas.length; i++){
            sumGas += gas[i];
            sumCost += cost[i];
            tank = tank + gas[i] - cost[i];
            //如果tank>=0,说明从start位置出发,能到达第i个位置
            if(tank < 0){
                start = i + 1;
                tank = 0;
            }
        }
        //如果sumGas >= sumCost,则一定存在一个路径能够走完这个环
        if(sumGas < sumCost){
            return -1;
        }else{
            return start;
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325606759&siteId=291194637