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

[leetcode] Gas Station

时间:2015-01-18 20:55:10      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

Gas Station

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.

思路:

从第0个点开始,遍历容器。用一个变量remain记录经过每个点后邮箱内剩余的油量。如果计算第i点的remain<0,则说明无法从第i点开出,因为无法到达下一个点。于是只能重新选择起点。(这个起点一定不是在上一个起点与i点之间的某一点。可以这么证明,假设上一个起点是t,第i点时remain<0,有一点j位于t和i之间,那么t到达j的时候这一点的remain>=0,而如果将起点定在j点,有remain=0,所以到第i点时仍然会有remain<0。)

于是题目简化了,不用所有的点都当成起点进行遍历。如果发现到第i个点时remain<0,那么下一个起点就是i+1,一直到能够循环一圈的或者起点大于给定容器的容量。

题解:

技术分享
class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int start = 0;
        int remain = 0;
        int n = gas.size();
        int i=0;
        while(start<n && i<start+n) {
            if(i<n)
                remain = remain+gas[i]-cost[i];
            else
                remain = remain+gas[i-n]-cost[i-n];
            if(remain<0) {
                start = i+1;
                remain = 0;
            }
            i++;
        }
        if(start>=n)
            return -1;
        return start;
    }
};
View Code

 

[leetcode] Gas Station

标签:

原文地址:http://www.cnblogs.com/jiasaidongqi/p/4232165.html

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