您的位置:首页 > 其它

Leetcode_gas-station

2014-04-10 16:49 465 查看
地址:http://oj.leetcode.com/problems/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.
思路:用类似首尾相连的队列来求解。
参考代码:

class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int ret = -1;
if(!gas.empty())
{
int front = 0, rear = gas.size()-1, val = 0;
vector<bool>visited(gas.size(), false);
while(front <= rear)
{
if(val>=cost[front])
{
val-=cost[front];
++front;
if(front<=rear && !visited[front])
{
val+=gas[front];
visited[front] = true;
}
else
break;
}
else
{
if(front<=rear && !visited[rear])
{
val+=gas[rear];
val-=cost[rear];
if(gas[rear]>=cost[rear])
ret = rear;
--rear;
}
else
break;
}
}
if(val<0)
ret = -1;
else if(rear == gas.size()-1)
ret = 0;
}
return ret;
}
};


16ms

//Solution Twoclass Solution {public:    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {        int gas_sum = accumulate(gas.begin(), gas.end(), 0);        int cost_sum = accumulate(cost.begin(), cost.end(), 0);        if(gas_sum < cost_sum)            return -1;        int begin = 0, end = 0;        int left = 0;        do        {            if(gas[begin]>=cost[begin])                left += (gas[begin]-cost[begin++]);            else if(gas[begin]+left>=cost[begin])                left -= (cost[begin]-gas[begin++]);            else// if(gas[end]-cost[end]+left>=cost[begin]-gas[begin])            {                end = (end + gas.size()-1) % gas.size();                left += gas[end]-cost[end];            }        }        while(begin < (end+gas.size()-1)%gas.size());        return end;    }};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: