Skip to content

Latest commit

 

History

History
34 lines (31 loc) · 734 Bytes

134.md

File metadata and controls

34 lines (31 loc) · 734 Bytes

134. 加油站

贪心

从i能走到j,下次检查从j+1开始。

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int size = gas.size();
        int i = 0;
        while (i < size) {
            int sum1 = 0, sum2 = 0;
            int cnt = 0;
            while (cnt < size) {
                int j = (i + cnt) % size;
                sum1 += gas[j];
                sum2 += cost[j];
                if (sum1 < sum2) {
                    break;
                }
                cnt++;
            }
            if (cnt == size) {
                return i;
            } else {
                i = i + cnt + 1;
            }
        }
        return -1;
    }
};