首页 > 其他 > 详细

【题解】【数组】【Leetcode】Gas Station

时间:2014-02-28 05:50:18      阅读:977      评论:0      收藏:0      [点我收藏+]

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.

思路:

1 从i开始,j是当前station的指针,sum += gas[j] – cost[j] (从j站加了油,再算上从i开始走到j剩的油,走到j+1站还能剩下多少油)
2 如果sum < 0,说明从i开始是不行的。那能不能从i..j中间的某个位置开始呢?假设能从k (i <=k<=j)走,那么i..j < 0,若k..j >=0,说明i..k – 1更是<0,那从k处就早该断开了,根本轮不到j。
3 所以一旦sum<0,i就赋成j + 1,sum归零。
4 最后total表示能不能走一圈。

bubuko.com,布布扣
 1 int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
 2     int n = gas.size();
 3     if(n < 1) return -1;
 4     
 5     int start = 0;
 6     int sum = 0;
 7     int total = 0;
 8     for(int j = 0; j < n; j++){
 9         sum += gas[j] - cost[j];
10         total += gas[j] - cost[j];
11         if(sum < 0){
12             sum = 0;
13             start = j+1;
14         }
15     }
16     return total>=0 ? start:-1;
17 }
bubuko.com,布布扣

【题解】【数组】【Leetcode】Gas Station,布布扣,bubuko.com

【题解】【数组】【Leetcode】Gas Station

原文:http://www.cnblogs.com/wei-li/p/GasStation.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!