代码改变世界

Gas Station

2015-04-03 15:54  笨笨的老兔子  阅读(211)  评论(0编辑  收藏  举报

有两个向量,一个向量存着gas,gas[i]代表在i点能够获得的gas,另外一个向量存着cost代表从i到i+1(注意循环)需要消耗的gas,希望找个一个地点i,从这个地点i开始能够跑完整个向量,如果不能跑完则返回-1。
思路:设定两个指针start和end,start指向向量尾部,end指向向量头部,设定一个sum记录当前的gas净开销。
如果sum>=0,说明可以往前走,则end++,然后sum加上新的净开销,如果sum<0,说明从start走是走不到end的,那么start退到start-1,加上净开销,看一下是否能够使得sum>0。总体思路就是净开销大于0,往前走,小于0,退一站再尝试。

  1. class Solution {
  2. public:
  3. int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
  4. int start = gas.size() - 1;
  5. int end = 0;
  6. int sum = gas[start]-cost[start];
  7. while (start > end)
  8. {
  9. if (sum >= 0)
  10. {
  11. sum += gas[end] - cost[end];
  12. end++;
  13. }
  14. else
  15. {
  16. start--;
  17. sum += gas[start] - cost[start];
  18. }
  19. }
  20. return sum >= 0 ? start : -1;
  21. }
  22. };