每日一道算法题--leetcode 134--加油站--python

【题目描述】 bash

【思路解析】

本题采用的是一种贪心策略,不考虑总体最优,只着眼于当前。读题目会发现,此题并不强调最优,能够有多种解,以多个点为起点均有可能实现环路走一圈。所以,制定一个贪心策略,知足条件便可。app

本题以gas[i]-cost[i]造成新列表new_list,找new_list中,以每一个位置为出发点到最后一个节点到最后一个节点的累加之和,找使得这个累加之和最大的节点为起点。即求从节点1到节点5,节点2到节点5,节点3到节点5,节点4到节点5的new_list值之和最大的节点。优化

若是从前向后加的话,会产生重复计算,时间复杂度O(n*n),代码以下:ui

new_list=[gas[i]-cost[i] for i in range(len(gas))]
 re=[sum(new_list[i:len(gas)]) for i in range(len(gas))]
复制代码

优化一下,从后向前计算,如此一来时间复杂度是O(n),只是对每一个节点作了一次加法而已,代码以下:spa

new_list=[gas[i]-cost[i] for i in range(len(gas))]
re=[0 for _ in range(len(gas)-1)]
re.append(new_list[len(gas)-1])
for i in range(len(gas)-2,-1,-1):
  re[i]=new_list[i]+re[i+1]
复制代码

【源代码】3d

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        if sum(gas)<sum(cost):
            return -1
        new_list=[gas[i]-cost[i] for i in range(len(gas))]
        re=[0 for _ in range(len(gas)-1)]
        re.append(new_list[len(gas)-1])
        for i in range(len(gas)-2,-1,-1):
            re[i]=new_list[i]+re[i+1]
        return re.index(max(re))
复制代码
相关文章
相关标签/搜索