码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Gas Station

时间:2015-03-20 01:11:41      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!