leetcode gas station

简单模拟题,改了半天

public int canCompleteCircuit(int[] gas, int[] cost) {
        int n = gas.length;
        int tmp = 0,idx=0;
        if(n==1)
            return gas[0]>=cost[0]?0:-1;
        for(int i=0;i<n;i++){  //枚举起点
            idx = (i+1)%n;
            tmp = gas[i]-cost[i];//+gas[idx];
            if(tmp>=0)
                tmp += gas[idx];
            else
                continue;
            while(idx!=i && tmp>=0){
                if((idx+1)%n != i)
                    tmp = tmp-cost[idx]+gas[(idx+1)%n];
                else
                    tmp -= cost[idx];
                idx = (idx+1)%n;
            }
            if(idx==i && tmp>=0){
                    return i;
            }
        }
        return -1;
    }
另外一个时间复杂度较低的解法,值得学习,即计算过的部分不浪费

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;
         
         
    }


猜你喜欢

转载自blog.csdn.net/weixin_42246923/article/details/80661005
今日推荐