Gas Station--LeetCode

野性酷女 2022-08-07 13:54 238阅读 0赞

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.

  1. #include <iostream>
  2. #include <vector>
  3. int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
  4. int index,cur;
  5. int len = gas.size();
  6. int begin=0,curNum;
  7. for(begin =0;begin<gas.size();begin++)
  8. {
  9. cur =0;
  10. curNum=0;
  11. index = begin;
  12. while(curNum<len)
  13. {
  14. index = index%len;
  15. cur +=cost[index];
  16. if(cur< cost[index])
  17. break;
  18. else
  19. cur -=cont[index];
  20. curNum++;
  21. index++;
  22. }
  23. if(curNum == len)
  24. return begin;
  25. }
  26. return -1;
  27. }

发表评论

表情:
评论列表 (有 0 条评论,238人围观)

还没有评论,来说两句吧...

相关阅读