s0134
ci/woodpecker/push/test Pipeline was successful Details

This commit is contained in:
Sainnhe Park 2023-02-07 11:44:09 +08:00
parent ef1cab537b
commit fa934cf225
2 changed files with 40 additions and 0 deletions

View File

@ -0,0 +1,13 @@
#ifndef S0134_GAS_STATION_HPP
#define S0134_GAS_STATION_HPP
#include <vector>
using namespace std;
class S0134 {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost);
};
#endif

27
src/s0134_gas_station.cpp Normal file
View File

@ -0,0 +1,27 @@
#include "s0134_gas_station.hpp"
// 我们假设 rest[i] = gas[i] - cost[i] 等于当前加油站所能积累的油量
// 情况一:
// 如果 totalSum = rest[0] + rest[1] + ... + rest[n-1] < 0 则说明所有加油站的油加起来都不够跑一圈的
// 情况二:
// 我们假设 totalSum >= 0 也就是所有加油站的油加起来能跑一圈
// 当前加油站索引为 i ,起始节点为 startIndex
// 那么如果 curSum = rest[startIndex] + rest[startIndex+1] + ... + rest[i] < 0 则说明剩下的节点加起来一定大于零
// 也就是 i 之前出现了多少负数,之后就应该出现多少正数
// 这时把 startIndex 设为 i+1 curSum = 0 继续迭代
int S0134::canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int curSum{0};
int totalSum{0};
int startIndex{0};
int len = gas.size();
for (int i{0}; i < len; ++i) {
curSum += gas[i] - cost[i];
totalSum += gas[i] - cost[i];
if (curSum < 0) {
startIndex = i + 1;
curSum = 0;
}
}
if (totalSum < 0) return -1;
return startIndex;
}