【Gas Station】cpp
题目:
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/鴿巢原理
===========================================================
第二次过这道题,一次AC了,大体思路记得比较清楚。写法完全按照自己理解了,与原来的代码已经不太一样了。
class Solution { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { const int gas_n = gas.size(); const int cost_n = cost.size(); if ( gas_n!= cost_n ) return -1; int total_compare = 0; int curr_gas = 0; int start = 0; for ( int i=0; i<cost_n; ++i ) { if ( curr_gas==0 ) start = i; curr_gas = curr_gas + gas[i] - cost[i]; if ( curr_gas<0 ) curr_gas = 0; total_compare = total_compare + gas[i] - cost[i]; } return total_compare>=0 ? start : -1; } };