标签:
题目描述:(链接)
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]
.
You have a car with an unlimited gas tank and it costs cost[i]
of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station‘s index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
解题思路:
如果所有花费的汽油之和>所有站点可提供的汽油之和,无解, return -1,这里用gap变量记录该差值,并且用sum变量记录当前差值,如果差值小于0,将当前站点设为index,sum设为0。
1 class Solution { 2 public: 3 int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { 4 int gap = 0; 5 int sum = 0; 6 int index = -1; 7 for (int i = 0; i < gas.size(); ++i) { 8 gap += gas[i] - cost[i]; 9 sum += gas[i] - cost[i]; 10 if (sum < 0) { 11 index = i; 12 sum = 0; 13 } 14 } 15 16 if (gap >= 0) { 17 return index + 1; 18 } 19 20 return -1; 21 } 22 };
标签:
原文地址:http://www.cnblogs.com/skycore/p/4888508.html