LeetCode134:Gas Station

mickole發表於2014-02-18

題目:

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.

解題思路:

一開始,我打算通過兩層迴圈,依次從某個點出發並測試是否能夠執行一圈,可想而知時間複雜度為O(n2),不滿足要求。之後看了http://blog.csdn.net/kenden23/article/details/14106137這篇部落格的解題思路,才發現有更簡單更優雅的解決方案,大概思路如下:

1 如果總的gas - cost小於零的話,那麼沒有解返回-1

2 如果前面所有的gas - cost加起來小於零,那麼前面所有的點都不能作為出發點。

關於第一點無需多言,這裡詳解下第二點,為什麼前面所有的點都不能作為起始站了,原因是:

假設從第0個站點開始,0~1,剩餘的煤氣left1 = gas[i]-cost[i],如果left為負,則過不去,必須從下一個站點從新開始,如果為正,則1~2時,left2 = gas[1]+left – cost[1],然後是2~3等等繼續下去,如果left一直為正,則表示這些站點都可以過去,但當某個站點i~i+1時,left為負數,說明過不去,且之前的所有站點都不能作為起始站,因為,每個站點要到下一個站點時,gas = gas +left,都不能過去,現在如果從某個站點開始,即gas量為它自身,更過不去。

實現程式碼:

#include <iostream>
#include <vector>
using namespace std;

/*
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.
*/ 
class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        if(gas.size() == 0 || cost.size() == 0 || gas.size() != cost.size())
            return -1;
        int left = 0;
        int total = 0;
        int start = 0;
        int n = gas.size();
        for(int i = 0; i < n; i++)
        {
            left += gas[i] - cost[i];//從i到i+i,剩餘的煤氣 
            total += gas[i] - cost[i];
            if(left < 0)//表示前面那些站點都不能作為起始站,現在開始從下一個站點開始 
            {
                start = i + 1; 
                left = 0;
            }
        }
        return total >= 0? start : -1;//煤氣總量是否大於等於總消耗 
        
    }
};
ing main(void)
{
    return 0;
}