国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > php教程 > leetcode No134. Gas Station

leetcode No134. Gas Station

来源:程序员人生   发布时间:2017-02-04 09:09:43 阅读次数:2143次

Question

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个圈里面有N个汽油站,i站的汽油有gas[i]汽油。现在有1辆无穷容量油箱的车,它从i站开到(i+1)需要耗费cost[i]汽油。如果这辆车可以走完这个圈,那末返回这个车的出发点,否者返回⑴.

Algorithm

  • 如果从A到不了B,那末A-B之间的任何1站都到不了B(B是从A开始第1个不能到达的站)
  • 如果各个站的油量总和超过需要消耗油量总和,则1定有解

Accepted Code

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int start=0,tank=0,total=0;
        for(int i=0;i<gas.size();i++)
        {
            tank+=gas[i]-cost[i];
            if(tank<0)
            {
                total+=tank;
                tank=0;
                start=i+1;
            }
        }
        return ((total+tank)<0)?-1:start;
    }
};

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生