- Gas Station
中文English
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.
Example
Example 1:
Input:gas[i]=[1,1,3,1],cost[i]=[2,2,1,1]
Output:2
Example 2:
Input:gas[i]=[1,1,3,1],cost[i]=[2,2,10,1]
Output:-1
Challenge
O(n) time and O(1) extra space
Notice
The solution is guaranteed to be unique.
解法1:Greedy Algorithm.
注意:
1)判断能不能跑一圈的条件就是totalSum > 0!
代码如下:
class Solution {
public:
/**
* @param gas: An array of integers
* @param cost: An array of integers
* @return: An integer
*/
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int N = gas.size();
if (N == 0) return -1;
int gasSum = 0;
int candidate = 0;
int totalSum = 0;
for (int i = 0; i < N; ++i) {
gasSum += gas[i];
if (gasSum < cost[i]) {
gasSum = 0;
candidate = (i == N) ? 0 : i + 1;
} else {
gasSum -= cost[i];
}
totalSum += gas[i] - cost[i];
}
candidate = candidate % N;
if (totalSum < 0) return -1;
return candidate;
}
};
博客围绕加油站问题展开,给定环形路线上各加油站的油量和行驶到下一站的耗油量,需判断能否绕一圈并找出起始加油站索引。介绍了使用贪心算法解决该问题,指出判断能否跑一圈的条件是totalSum > 0,还给出了示例及复杂度要求。
2万+

被折叠的 条评论
为什么被折叠?



