• 1872. 连接棒材的最低费用


    1872. 连接棒材的最低费用

    中文English

    为了装修新房,你需要加工一些长度为正整数的棒材 sticks。
    如果要将长度分别为 X 和 Y 的两根棒材连接在一起,你需要支付 X + Y 的费用。 由于施工需要,你必须将所有棒材连接成一根。
    返回你把所有棒材 sticks 连成一根所需要的最低费用。注意你可以任意选择棒材连接的顺序

    样例

    样例 1:

    输入:
     [2,4,3]
    输出:14
    解释:先将 2 和 3 连接成 5,花费 5;再将 5 和 4 连接成 9;总花费为 14
    

    样例 2:

    输入:
     [1,8,3,5]
    输出:30
    

    注意事项

    • 1 leq sticks.length leq 10^41sticks.length104​​
    • 1 leq sticks[i] leq 10^41sticks[i]104​​

    heapq 堆队列

    import heapq
    class Solution:
        """
        @param sticks: the length of sticks
        @return: Minimum Cost to Connect Sticks
        """
        def MinimumCost(self, sticks):
            # write your code here
            if not sticks: return 0
            
            #将list sticks原地转化为堆,线性时间内
            heapq.heapify(sticks)
            cost, length = 0, len(sticks)
            
            for i in range(length - 1):
                num1, num2 = heapq.heappop(sticks), heapq.heappop(sticks)
                cost += num1 + num2
                heapq.heappush(sticks, num1 + num2)
            
            return cost

    PirortityQueue 优先队列

    import queue
    class Solution:
        """
        @param sticks: the length of sticks
        @return: Minimum Cost to Connect Sticks
        """
        def MinimumCost(self, sticks):
            # write your code here
            if not sticks: return 0
            
            array = []
            cost = 0
            #优先队列
            minqueue = queue.PriorityQueue()
            #所有的值丢尽minqueue里面
            for val in sticks:
                minqueue.put(val)
            
            while minqueue.qsize() > 1:
                #每次get出最小的值出来,然后在put到minqueue里面
                total = minqueue.get() + minqueue.get()
                cost += total
                minqueue.put(total)
            
            return cost
  • 相关阅读:
    ICO图标的制作、下载
    网页Loading,让页面加载完再显示
    鹏城之行
    The shit live,learn to give up!
    缘分
    一篇网络文章,能否让我真正顿悟???
    李开复给中国学生的第三封信:成功、自信、快乐
    Uncountable missing,missing...
    李开复给中国学生的第五封信:做个积极主动的你
    李开复给中国学生的第四封信:大学应这样过
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/14131179.html
Copyright © 2020-2023  润新知