2019-07-24 EP134 Gas Station

image.png

这个题比较容易陷阱一个陷阱,如果一直想去check每一个点出发,看结果是否满足,那么时间复杂度肯定得O(n^2)了,

题目保证是有解的,那么从某个点开始,如果到最后一直为正的结果的话,那么这个肯定是一个解

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int sum = 0; 
        int total = 0;
        int j = -1;
        
        for (int i = 0; i < gas.size(); i++) {
            sum += gas[i] - cost[i];
            total += gas[i] - cost[i];
            if (sum < 0) {
                sum = 0;
                j = i;
            } 
        }
        return total < 0 ? -1 : j + 1;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。