题目
在一条环路上有 n 个加油站,其中第 i 个加油站有 gas[i] 升油,假设汽车油箱容量无限,从第 i 个加油站驶往第 (i+1)%n 个加油站需要花费 cost[i] 升油。
请问能否绕环路行驶一周,如果可以则返回出发的加油站编号,如果不能,则返回 -1。
题目数据可以保证最多有一个答案。
数据范围: 1≤n≤104 1≤n≤104 , gas 和 cost 数组中的值满足 1≤val≤105 1≤val≤105
代码
# include <iostream>
# include <vector>
using namespace std;
/**
* @brief 确定出发的加油站位置
* @param num1 加油量
* @param num2 油消耗量
* @return 加油站索引
*/
int gas_station(vector<int>& gas, vector<int>& cost) {
int sum_total = 0;//用于计算油量总剩余量
int rest = 0;//当前油剩余量
int station = 0;//加油站号
for (int i = 0; i < gas.size(); ++i)
{
rest += gas[i] - cost[i];
sum_total += gas[i] - cost[i];
//如果当前油剩余量小于0,则换下一个加油站作为出发点,当前加油站和之前加油站都不行
if (rest < 0) {
//重置当前油剩余量,加油站换下一个
rest = 0;
station = i + 1;
}
}
//如果油量总剩余量小于0,则不能跑一圈
if (sum_total < 0) {
return -1;
}
else {
return station+1;
}
}
int main()
{
vector<int> gas = { 1, 2, 3, 4, 5 };
vector<int> cost = { 3,4,5,1,2 };
int station = gas_station(gas, cost);
std::cout << station << std::endl;
system("pause");
return 0;
}