Bootstrap

leecode134.加油站

 一开始想的是总体上加油量超过耗油量那么就一定能找到一个起始点可以跑一圈,这个起始点选择补充油量与耗油量差值最大的那gas个点,但是我没仔细审题,这个起始点是索引逐次+1绕一圈而不是随便选择,gas[5,8,2,8],cost[6,5,6,6]这里错误地选择了1为起点

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int result=-1;
        int difference=INT32_MIN;
        int differenceSum=0;
        int n=gas.size();
        for(int i=0;i<n;i++){
            int temp=gas[i]-cost[i];
            if(temp>difference){
                difference=temp;
                result=i;
            }
            differenceSum+=temp;
        }
        if(differenceSum<0)
            return -1;
        else
            return result;
    }
};

 改进方法是累加每次剩余油量,如果在i处剩余油量为负数那么不能选择i及之前的作为起始点,转战i+1,剩余油量变为0

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int result=0;
        int difference=0;
        int differenceSum=0;
        int n=gas.size();
        for(int i=0;i<n;i++){
            int temp=gas[i]-cost[i];
            differenceSum+=temp;
            difference+=temp;
            if(difference<0){
                result=i+1;
                difference=0;
            }
        }
        if(differenceSum<0)
            return -1;
        else
            return result;
    }
};

;