From fa934cf225cc37f080d3742211a983febf9e4f07 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Tue, 7 Feb 2023 11:44:09 +0800 Subject: [PATCH] s0134 --- include/s0134_gas_station.hpp | 13 +++++++++++++ src/s0134_gas_station.cpp | 27 +++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 include/s0134_gas_station.hpp create mode 100644 src/s0134_gas_station.cpp diff --git a/include/s0134_gas_station.hpp b/include/s0134_gas_station.hpp new file mode 100644 index 0000000..788fab7 --- /dev/null +++ b/include/s0134_gas_station.hpp @@ -0,0 +1,13 @@ +#ifndef S0134_GAS_STATION_HPP +#define S0134_GAS_STATION_HPP + +#include + +using namespace std; + +class S0134 { + public: + int canCompleteCircuit(vector& gas, vector& cost); +}; + +#endif diff --git a/src/s0134_gas_station.cpp b/src/s0134_gas_station.cpp new file mode 100644 index 0000000..3c1e948 --- /dev/null +++ b/src/s0134_gas_station.cpp @@ -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& gas, vector& 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; +}