您的位置:首页 > 其它

Gas Station

2015-07-21 15:27 393 查看
描述

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.

【题意】

在环形路线上一共有N个加油站,每个加油站的存储容量为gas[i].你有一辆汽油无限存储的汽车,如果你从加油站i到下一站(i+1),你需要

消耗汽油cost[i] 你从某一个加油站开始你的旅程,但是你的汽车里没有任何的汽油。

如果你能沿着环形路线旅游一遍,返回你开始旅游的加油站的下标否则返回-1

分析:

如果最后剩油量大于0,则说明肯定有一条路线。

对于一个循环数组,如果这个数组整体和 SUM >= 0,那么必然可以在数组中找到这么一个元素:从这个数组元素出发,绕数组一圈,能保证累加和一直是出于非负状态。

如果这个前面的数累加和小余0,则后面的累加一定大于0.

class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int total = 0;
int j = -1;
for (int i = 0, sum = 0; i < gas.size(); ++i) {
sum += gas[i] - cost[i];
total += gas[i] - cost[i];
if (sum < 0) {
j = i;
sum = 0;
}
}
return total >= 0 ? j + 1 : -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: