leetcode-Gas Station

来源:互联网 发布:php自动发卡平台 编辑:程序博客网 时间:2024/06/05 22:33

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的内存分配是当容量不够时,要在另一块内存分配两倍大小的空间,然后把原来内存的元素拷贝过去,再释放原内存空间,这样分配、拷贝、释放内存当然没只分配一次内存效率高。



0 0
原创粉丝点击