leetcode Gas Station

来源:互联网 发布:梦幻群侠传3优化版攻略 编辑:程序博客网 时间:2024/09/21 09:00

此题思路较为简单,即判断是否存在从某一点开始,在保证每经过一个加油站都加上所有油的前提下,汽车都保持行驶状态,直至行驶完一圈。

需要注意的是程序结束条件。

代码

class Solution {public:    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {                int start = 0;        int j = start;        int gasAll = gas[j];        int size = gas.size();        int count = 0;             while(true)        {            if(count==size)                return start;            else            {                if(gasAll>=cost[j])                  {                      gasAll -= cost[j];                      j = (j+1)%size;                      gasAll += gas[j];                      count++;                  }                  else                  {                      start = (start+1)%size;                      if(start==0)                          return -1;                      j = start;                      gasAll = gas[j];                      count = 0;                  }            }                    }    }};


0 0
原创粉丝点击