leetcode-gas station
2014-06-06 10:57
411 查看
Gas Station
Total Accepted: 12395 TotalSubmissions: 50855My Submissions
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.
Have you been asked this question in an interview?
最开始的方法,超时了:
class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int len = gas.size(); int tank ; int start,i; for(start=0;start<len;start++) { tank = 0; for(i=0;i<len;i++) { if(i+start<len) { tank += gas[i+start]; tank -= cost[i+start]; if(tank<0)break; } else { tank += gas[i+start-len]; tank -= cost[i+start-len]; if(tank<0)break; } } if(i!=len)continue; else break; } if(start==len)return -1; return start; } };
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { // Note: The Solution object is instantiated only once. int total = 0; int currentgas = 0; int startpoint = -1; int sz = gas.size(); for(int i = 0; i < sz; i++) { currentgas += gas[i] - cost[i]; total += gas[i] - cost[i]; if(currentgas < 0) { startpoint = i; currentgas = 0; } } return total >= 0 ? startpoint+1 : -1; }
解题报告:
当然,这题如是一个一个开始,然后把所有点走一遍,再判断是否成立,这个是可以的,也是最正常的思维,但复杂度O(n2)
这就是第一种解法
不得不优化。
有如下规律,如果一串数字,总和大于等于0,则必存在某一点,从这点开始,一真累加,每次都是非负数
这样,我们只需要判断最后的结果是否为非负就知道是否存在解,即total>=0
要找到开始的那个点,就判断是否是一直>=0,
相关文章推荐
- leetcode-Gas Station
- [LeetCode]Gas Station
- LeetCode Gas Station
- Gas Station - Leetcode
- LeetCode Gas Station
- Leetcode @ Gas Station
- [LeetCode]Gas Station 最大子序列和,贪心
- leetcode_Gas Station
- [leetcode] 134 Gas Station
- leetcode-134-Gas Station
- LeetCode (Gas Station)
- [LeetCode] Gas Station
- LeetCode 之 Gas Station
- LeetCode - Gas Station 题解
- leetcode之Gas Station
- [leetcode] Gas Station java
- Java for LeetCode 134 Gas Station
- leetcode Gas Station
- leetcode-Gas Station
- LeetCode之Gas Station