力扣134. 加油站

迭代

  • 思路:
    • 暴力模拟迭代;
    • 假设从第 idx 个加油站开始,使用一个变量对行驶的加油站个数计数,如果最后行驶的个数为 size,则是可行的;
    • 否则,行驶过的加油站都不可行;(加快更新 idx 重试)
      • 是否可行,通过累计获取的汽油容量与消耗的容量进行比较,Sum(gas[i]) > Sum(cost[i]);
class Solution {
public:
    int canCompleteCircuit(vector& gas, vector& cost) {
        int size = gas.size();
        int idx = 0;

        while (idx < size) {
            int sumOfGas = 0;
            int sumOfCost = 0;
            int cnt = 0;
            while (cnt < size) {
                int j = (idx + cnt) % size;
                sumOfGas += gas[j];
                sumOfCost += cost[j];
                if (sumOfCost > sumOfGas) {
                    break;
                }

                cnt++;
            }

            if (cnt == size) {
                return idx;
            } else {
                idx = idx + cnt + 1;
            }
        }

        return -1;
    }
};

你可能感兴趣的:(力扣实践,leetcode,算法,职场和发展)