Sunday, February 22, 2015

Gas Station

Gas Station

 here are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
--------------------------- thinking --------------------------------------------
method 1: using start and end to control the range of the whole loop
https://oj.leetcode.com/discuss/16087/space-running-time-solution-anybody-have-posted-this-solution
method 2: using updating start position to do the calculation
https://oj.leetcode.com/discuss/21577/my-o-n-time-o-1-extra-space-solution
------------- codes ----------------------------------------
class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
       int start = gas.size()-1;
       int end = 0;
       int sum = gas[start] - cost[start];
       while (start > end) {
          if (sum >= 0) {
             sum += gas[end] - cost[end];
             ++end;
          }
          else {
             --start;
             sum += gas[start] - cost[start];
          }
       }
       return sum >= 0 ? start : -1;
    }

};

------------------- codes --------------------------
class Solution {
public:
    /**
     * @param gas: a vector of integers
     * @param cost: a vector of integers
     * @return: an integer 
     */
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        // write your code here
        //pay off point
        if (gas.size() == 0) return -1;
        int poff = 0;
        int front_check = 0;
        int own = 0;
        while (poff < gas.size()) {
            if (gas[poff] >= cost[poff]) {
                //find the poff point and keep checking if it can supply the whole run
                front_check = poff + 1;
                own = gas[poff] - cost[poff];
                while (true) {
                    own = own + gas[front_check % gas.size()] - cost[front_check % gas.size()];
                    if (own >= 0) {
                        front_check++;
                        if (front_check%gas.size() == poff) {
                            return poff;
                        }
                    } else {
                        poff = front_check + 1;
                        break;
                    }
                }
            } else {
                poff++;
            }
        }
        return -1;
    }

};

No comments:

Post a Comment