【題解】LeetCode 134. Gas Station

【題目敘述】https://leetcode.com/problems/gas-station/

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int sz = cost.size();
        for (int i = 0; i < sz; i++){
            cost[i] = gas[i]-cost[i];
        }
        int idx = 0, mn = cost[0], tot = 0;
        for (int i = 0; i < sz; i++){
            tot += cost[i];
            if (tot < mn){
                mn = tot;
                idx = i;
            }
        }
        int now;
        bool flag = true;
        tot = 0;
        for (int i = 0; i < sz; i++){
            now = (i + idx + 1) % sz;
            tot += cost[now];
            if (tot < 0){
                flag = false;
                break;
            }
        }
        if (flag) return (idx+1) % sz;
        else return -1;
    }
};
分享本文 Share with friends