leetcode 之Gas Station(11)

这题的思路很巧妙,用两个变量,一个变量衡量当前指针是否有效,一个衡量整个数组是否有解,需要好好体会。

int gasStation(vector<int> &gas, vector<int> &cost)
      {
          int total = 0;
          int j;
          int sum = 0;
          for (int i = 0; i < gas.size(); i++)
          {
              sum += gas[i] - cost[i];
              total += gas[i] - cost[i];
              if (sum < 0)
              {
                  j = i;
                  sum = 0;
              }
          }
          return total>0 ? j + 1 : -1;
      }
View Code
原文地址:https://www.cnblogs.com/573177885qq/p/5498026.html