134. Gas Station

来源:互联网 发布:客厅电脑主机 知乎 编辑:程序博客网 时间:2024/06/07 01:19

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[i],每个站点要消耗cost[i],问能否环一周。

思路:暴力的解法是从每个点开始,进行环游一周,记录各个点的油量,然后看油量是否满足消耗。不满足则说明这个点开始不行。如果所有点都进行完了,则结果能不能环游一周也就知道了。第二种思路是,用一个全局的变量记录总的油耗对比,并用局部的sum记录结点间的油耗情况,如果有一个点过不去,则从下一个点开始进行。

class Solution {public:int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {int total = 0;int sum = 0;int index = 0;for (int i = 0; i < gas.size(); i++){sum += gas[i] - cost[i];total += gas[i] - cost[i];if (sum < 0){index = i + 1;sum = 0;}}return total >= 0 ? index : -1;}};


0 0
原创粉丝点击