LeetCode——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.

Solution

这道题采用贪心的思想,如果这站到下一站不能满足要求的话,就从下一站开始,然后记录已经走过的地方所缺的油量的数目。

Code

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int tankCount = 0;
		int need = 0;
        int start = 0;
        for (int i = 0; i < gas.size(); i++) {
            tankCount += gas[i];
            if (tankCount >= cost[i]) {
				tankCount -= cost[i];
                need -= (gas[i] - cost[i]);
            } else {
                need += (cost[i] - gas[i]);
                tankCount = 0;
                start = i + 1;
            }
        }
        if (tankCount >= need)
        	return start;
        else
            return -1;
    }
};
posted @ 2017-06-26 13:57  清水汪汪  阅读(135)  评论(0)    收藏  举报