leetcode-Gas Station

Gas Station

 Total Accepted: 12195 Total Submissions: 50108My Submissions

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.

Have you been asked this question in an interview?

 


汽车加油站:循环线路上有N个加油站,每一个加油站有油量为gas[i],汽车油桶容量无限。从油站i到下一站(i+1)要花费cost[i],汽车从某个油站出发,要求返回可以走完所有油站的起始油站位置(唯一),否则返回-1.

能够走完所有油站的话说明所有油站的油量加起来不小于走全然程要耗的油量,我们能够用一个left动态数组来保存一个油站加油后到下一个油站能够剩下的油量,left[i]表示汽车在油站i加油走到(i+1)站剩下的油量。

非常显然,假设汽车能够走全然程的话,起始点i必须满足left[i]>=0。否则汽车开不到下一站。所以。这样能够遍历left数组,找到起始点left[i]>=0,然后继续走下去到j,假设出现起始点到该站的left总和<0,说明要更新起始点。

而中间的[i,j]网站所有都不能当做起始点,假设中间某个站k的left[k]>=0。从k出发是到不了j的。所以更新起始点到j后面的>=0的left。


class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        vector<int> left;
        left.reserve(gas.size());
        int i;
        for (i=0; i<gas.size(); ++i) {
            left.push_back(gas[i] - cost[i]);
        }
        int idx(0), sum(0), subsum(0);
        for (i=0; i<left.size(); ++i) {
            if (subsum+left[i]>=0) {
                subsum += left[i];
            } else {
                subsum = 0;
                idx = i + 1;
            }
            sum += left[i];
        }
        if (sum < 0) return -1;
        return idx;
    }
}

关于STL vector使用技巧:一般来说。假设知道vector要容纳的元素数量,能够先调用reserve函数预先分配这么多的容量,容量大小能够通过capacity函数获得,size函数是获取容器当前容纳元素的数量。假设不先reserver。我们知道vector的内存分配是当容量不够时,要在还有一块内存分配两倍大小的空间,然后把原来内存的元素拷贝过去,再释放原内存空间,这样分配、拷贝、释放内存当然没仅仅分配一次内存效率高。





posted @ 2017-07-15 08:17  wzjhoutai  阅读(147)  评论(0编辑  收藏  举报