134题 环形公路加油站
原题地址
https://leetcode.com/problems/gas-station/description/
- 题解
class Solution:
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
start, remain_gas, total = 0, 0, 0
for i in range(len(gas)):
total += gas[i] - cost[i]
if remain_gas < 0:
start = i
remain_gas = gas[i] - cost[i]
else:
remain_gas += gas[i] - cost[i]
return start if total >= 0 else -1
- 题解
class Solution_2 {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int start = gas.size() - 1;
int end = 0;
int sum = gas[start] - cost[start];
while (start > end) {
if (sum >= 0) {
sum += gas[end] - cost[end];
++end;
} else {
--start;
sum += gas[start] - cost[start];
}
}
return sum >= 0 ? start : -1;
}
};
网友评论