LeetCode OJ:Gas Station

Gas Station

  Total Accepted: 5589  Total Submissions: 23851 My Submissions

There 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.


算法思想:以gas[i]-cost[i]为考虑对象,此题也就是找出可以从该点出发一直加到该点的前一点,其中不会出现小于0的点,一种比较直白的方式是把每个点都这么找一遍来确定答案,其实可以这么考虑,若所有这些点的和sum>=0,说明必定可以找到满足题目的一点,既然如此,

假设序列a1,a2,a3.....ai,a(i+1)....an,若有a1+a2+..+ai<0,则必然有a(i+1)+..+an>0(否则不满足sum>=0)且|a(i+1)+..+an|>=|a1+a2+...+ai|,那么我们只需找到使sum和最小的那个点的后一个点,则必然可以满足,从这个点开始,总能保证sum>=0

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int sum=0;
        int index=0,val=0;
        for(int i=0;i<gas.size();i++){
            sum+=gas[i]-cost[i];
            if(sum<val){
                val=sum;
                index=i+1;
            }
        }
        if(sum>=0){
            return index%gas.size();
        }
        return -1;
    }
};

answer2

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int total=0;
        int j=-1;
        for(int i=0,sum=0;i<gas.size();++i){
            sum+=gas[i]-cost[i];
            total+=gas[i]-cost[i];
            if(sum<0){
                j=i;
                sum=0;
            }
        }
        return total>=0?j+1:-1;
    }
};



你可能感兴趣的:(LeetCode)