农民代表
- 积分
- 8691
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2019-3-22
- 最后登录
- 1970-1-1
|
标题是不是写错了?是电面不是店面吧。
第二题的Python实现,很简单,供初学者参考:
- from heapq import heapify, heappush, heappop
- class Solution:
- def connect_sticks(self, sticks):
- if not sticks: return 0
-
- total_cost = 0
- heapify(sticks)
-
- while len(sticks) > 1:
- stick1 = heappop(sticks)
- stick2 = heappop(sticks)
- total_cost += (stick1 + stick2)
- heappush(sticks, stick1+stick2)
-
- return total_cost
- if __name__ == "__main__":
- print(Solution().connect_sticks([1]))
- print(Solution().connect_sticks([1,3,4]))
复制代码 |
|