LeetCode134:Gas Station
题目:
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; }