程序员人生 网站导航

leetcode No134. Gas Station

栏目:php教程时间:2017-02-04 09:09:43

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;
    }
};

------分隔线----------------------------
------分隔线----------------------------

最新技术推荐