Gas Station--LeetCode

来源:互联网 发布:nginx cache 编辑:程序博客网 时间:2024/06/07 20:09

There are N gas stations along a circular route, where the amount of gas at stationi isgas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from stationi 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.


#include <iostream>#include <vector>int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {    int index,cur;    int len = gas.size();    int begin=0,curNum;    for(begin =0;begin<gas.size();begin++)    {       cur =0;       curNum=0;       index = begin;       while(curNum<len)       {          index = index%len;          cur +=cost[index];          if(cur< cost[index])           break;          else            cur -=cont[index];          curNum++;          index++;     }       if(curNum == len)       return begin;    }    return -1;   } 

0 0