Share my C++ solution,easy to understand


  • 0
    V
    class Solution {
    public:
        int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
            int n = gas.size();
            int ret = 0;
            int i = 0;
            int remain = 0;
            int first = 1;
    
            while (true)
            {
                if ((i + 1) >= n)//travel around the circuit at least once
                    first = 0;
                     
                if (cost[i] > (gas[i] + remain))
                {
                    if (i >= 0 && first == 0)
                        break;
                        
                    i = (i + 1) % n;
                    ret = i;
                    remain = 0;
                    continue;
                }
        
                if ((i + 1) % n == ret)
                    return ret;
                
                remain += (gas[i] - cost[i]);
                i = (i + 1) % n;
            }
            
            return -1;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.