题目链接:leetcode
思路:
贪婪
1 | class Solution(object): |
一个更清晰的solution:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
start, cur_sum, total_sum = 0, 0, 0
for i in range(len(gas)):
diff = gas[i]-cost[i]
cur_sum += diff
total_sum += diff
if cur_sum < 0:
start = i+1
cur_sum = 0
if total_sum >= 0:
return start
return -1