LeetCode134.. Gas Station

来源:互联网 发布:linux 多线程 书籍 编辑:程序博客网 时间:2024/05/04 07:43

LeetCode134. 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.

Subscribe to see which companies asked this question.

  • Total Accepted: 78753
  • Total Submissions: 273815
  • Difficulty: Medium
  • Contributors: Admin

题目的意思是,有一辆车要过一个环形的道路,路上都有一定数量的加油站,每个加油站有一定量的油,数组中元素gas[i]加油站i里面的油,数组中元素cost[i]表示从加油站i到加油站i+1需要的油,问在那个加油站出发可以成功环行整个道路,返回加油站的下标值,如果没有则返回-1.


一开始没有怎么想,直接用了穷举法,复杂度是O(n^2),可以通过,但是耗时严重,排在最后90%多。代码如下:

class Solution {public:    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {        if(gas.size()==0||cost.size()==0)        return -1;        vector<int >record;        for (int i = 0;i<gas.size();i++)        {            record.push_back(gas[i]-cost[i]);        }        for (int i = 0;i<gas.size();i++)        {            int j = i+1;            if (j==gas.size())j=0;            int temp = record[i];            if (record[i]<0)                continue;            bool work = true;            while (j!=i)            {                temp+=record[j];                if (temp<0)                    {                        work =false;                        break;                    }                j++;                if (j==gas.size())                    j = 0;            }            if (work)            return i;        }        return -1;    }};

其实这个的问题只用遍历一遍即可,用一个数值来记录总耗费与总补充油量,最后如果是负的说明问题没有答案,返回-1。在遍历每个加油站的时候,用一个变量来记录经过这个加油站后油箱是否还有油,没有的话就从该站点出发尝试,代码如下:

class Solution {public:    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {        if (gas.size() == 0) return -1;        int total = 0;        int temp = 0;        int ans = 0;//假设车从0出发.        for (int i = 0; i < gas.size(); ++i){            total += (gas[i] - cost[i]);            if (temp < 0){ //油箱已空,则调整车辆从该站点出发                temp = (gas[i] - cost[i]);                ans = i;            }            else  //油箱还有,继续前进                temp += (gas[i] - cost[i]);        }        if(total <0)//total等于零说明这段路总耗油大于总油量,不可能环形,不等于零则返回最后车辆的出发点。            return -1;        else             return ans;    }};

16 / 16 test cases passed.
Status: 

Accepted

Runtime: 6 ms

0 0
原创粉丝点击