问题描述
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.
翻译
加油站,在一条环形路线上有 N 个加油站,其中第 i 个加油站的油量为 gas[i]。你有一辆油箱容量无限的汽车,从第 i 个加油站到下一个加油站(i+1)需要花费汽油费用[i]。您在其中一个加油站以空油箱开始旅程。如果可以绕行一圈,则返回起始加油站的索引,否则返回-1。
注意:保证解是唯一的。
思路
核心思想:计算前缀和
将每个站的汽油含量-消耗量存放在tem数组中,同时使用currtotal作为总体标量来查看时候汽油数 >路程消耗数 。如果currtotal<0,说明不可能
同时curr作为当前油箱内 油量,如果curr<0,则将curr清0从i+1开始继续遍历
使用while循环
具体证明可以去b站看代码随想录
代码:贪心和暴力
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string>
#include <algorithm>
#include <stdlib.h>
#include <vector>
using namespace std;
int canCompleteCycleBurte(vector<int> gas, vector<int> cost)
{
int res = -1;
int n = gas.size();
if (n == 1 && gas[0] >= cost[0])
return 0;
for (int i = 0; i < n; i++)
{
int curr = 0;
if (gas[i] == cost[i])
continue;
int j = i;
do
{
if (curr + gas[j % n] >= cost[j % n])
{
curr += (gas[j % n] - cost[j % n]);
j++;
if (j == n + i)
return i;
}
else
{
j++;
break;
}
} while (j % n != i);
}
return res;
}
int canCompleteCycleGreedy(vector<int>gas, vector<int>cost)
{
int n = gas.size();
int total = 0;
int res = 0; int curr = 0;
for (int i = 0; i < n; i++)
{
total += gas[i] - cost[i];//总油数-总耗油
curr += gas[i] - cost[i];//遍历到当前的车站,油箱剩余油量
if (curr < 0)
{
res = i + 1;//说明前面任意一个车站出发都不能到达第i个,因此从i+1开始
curr = 0;
}
}
if (total < 0)//总油数少于总耗油
return -1;
else
return res;
}
int main()
{
int n;
cout << "Please enter the number of the gas station :" << endl;
cin >> n;
vector<int>gas(n),cost(n);
cout << "Please enter the gas that each station has :" << endl;
for (int i = 0; i < n; i++)
cin >> gas[i];
cout << "Please enter the cost of gas go to the next station :" << endl;
for (int i = 0; i < n; i++)
cin >> cost[i];
//int res = canCompleteCycleBurte(gas, cost);
int res = canCompleteCycleGreedy(gas, cost);
if (res == -1)
cout << "There is no way to complete ! " << res << endl;
else
cout << "We should begin at " << res << " station " << endl;
return 0;
}
测试案例
输入: gas = [1,2,3,4,5], cost = [3,4,5,1,2] 输出: 3 解释: 从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油 开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油 开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油 开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油 开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油 开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。 因此,3 可为起始索引。
运行结果
时间复杂度分析
Only use one loop toIterate over the array cost O(n);