标签:
题目:
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() != cost.size() ) return -1; int start_station = -1; int tmp_sum = 0; int total = 0; for (size_t i = 0; i < gas.size(); ++i) { tmp_sum += gas[i] - cost[i]; total += gas[i] - cost[i]; if (tmp_sum<0) { tmp_sum=0; start_station = i; } } return total>=0 ? start_station+1 : -1; } };
Tips:
1. 采用贪心算法的思想:维护一个tmp_sum,计算从开始节点到当前节点损耗之差;如果小于零,则直接放弃;否则,继续累加。
2. 最终判断能不能完成行程,需要维护一个total:如果total大于等于0,则判定一定可以走完这趟旅程。这是为什么呢?具体原理可以参见鸽巢原理。
参考资料
贪心算法:http://zh.wikipedia.org/wiki/贪心法
鸽巢原理:http://zh.wikipedia.org/wiki/鴿巢原理
标签:
原文地址:http://www.cnblogs.com/xbf9xbf/p/4458778.html