leetcode/src/s0134_gas_station.cpp

28 lines
1.0 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}