标签:
Not quite hard. Just remember initialize index to 0. Because if you initialize it as -1 and all the gas satisfy the cost, it will return -1.
Actually, it was 0.
1 class Solution { 2 public: 3 int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { 4 int len = gas.size(), total = 0, sum = 0, index = 0; 5 if (len == 0 || len != cost.size()) return -1; 6 for (int i = 0; i < len; i++) { 7 total += gas[i] - cost[i]; 8 sum += gas[i] - cost[i]; 9 if (sum < 0) { 10 sum = 0; 11 index = i + 1; 12 } 13 } 14 return total < 0 ? -1 : index; 15 } 16 };
LeetCode – Refresh – Gas Station
标签:
原文地址:http://www.cnblogs.com/shuashuashua/p/4352209.html