leetcode134

class Solution {
public:
    inline int get_next(int idx, int size)
    {
        return idx == size-1 ? 0 : idx+1;
    }
    
    int aux(int idx, vector<int>& gas, vector<int>& cost)
    {
        int i = idx;
        int left = gas[i] - cost[i];
        if(left < 0)
            return -1;
        i = get_next(i, gas.size());
        while( i!= idx)
        {
            left = left + gas[i] - cost[i];
            if(left < 0)
                return -1;
            i = get_next(i, gas.size());
        }
        return idx;
    }
    
    
    
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int ret;
        int i = 0;
        for(; i<gas.size(); ++i)
        {
            if(gas[i] >= cost[i])
            {
                ret = aux(i, gas, cost);
                cout << ret << endl;
                if(ret == -1)
                    continue;
                else
                    break;
            }
        }
        return ret;
    }
};

补充一个python的实现:

 1 class Solution:
 2     def canCompleteCircuit(self, gas: 'List[int]', cost: 'List[int]') -> int:
 3         n = len(gas)
 4         total = 0
 5         sums = 0
 6         begin = 0
 7         for i in range(n):
 8             diff = gas[i] - cost[i]
 9             total += diff
10             sums += diff
11             if sums < 0:
12                 begin = i + 1
13                 sums = 0
14         if total < 0:
15             return -1
16         return begin

题目确保,如果存在解,是唯一的解,因此程序只需要找出可以完成全程的第一个起点就行。

因为全程的加油数量和耗油数量都是固定的,因此从哪个点计算全程的总的消耗都是一样的。不需要先找到起点,然后再进行计算。

因此可以在一次循环中,完成两种计算:1判断是否可以走完全程(total是否小于0),2寻找第一个可以作为起点的坐标(begin)。

原文地址:https://www.cnblogs.com/asenyang/p/9826603.html