[leetcode] 134. Gas Station (medium)

原题
题意:
过一个循环的加油站,每个加油站可以加一定数量的油,走到下一个加油站需要消耗一定数量的油,判断能否走一圈。

思路:
一开始思路就是遍历一圈,最直接的思路。

class Solution
{
  public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
    {
        int beg = 0;
        int tank = 0;
        int n = gas.size();
        int sumGas = 0, sumCost = 0;
        for (auto a : gas)
            sumGas += a;
        for (auto a : cost)
            sumCost += a;

        if (sumGas < sumCost)
        {
            return -1;
        }

        for (int i = 0; i < n; i++)
        {
            tank += gas[i];

            if (tank >= cost[i])
            {
                tank -= cost[i];
            }
            else
            {
                beg = i + 1;
                tank = 0;
            }
        }
        return beg;
    }
};

看到别人的题解,很简洁。

class Solution {
 public:
  int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
    int max = 0;
    int sum = 0;
    int beg = 0;
    for (int i = gas.size() - 1; i >= 0; i++) {
      sum += gas[i] - cost[i];
      if (max < sum) {
        max = sum;
        beg = i;
      }
    }
    return sum < 0 ? -1 : beg;
  }
};
posted @ 2018-10-15 00:27  Ruohua3kou  阅读(116)  评论(0编辑  收藏  举报