0
点赞
收藏
分享

微信扫一扫

LeetCode题解(1801):积压订单中的订单总数(Python)


题目:​​原题链接​​(中等)

标签:堆、贪心算法

解法

时间复杂度

空间复杂度

执行用时

Ans 1 (Python)

200ms (75.55%)

Ans 2 (Python)

Ans 3 (Python)

解法一:

class Solution:
_MOD = 10 ** 9 + 7

def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:
buy_heap = []
sell_heap = []

for price, amount, order_type in orders:
if order_type == 0: # buy:买入
while amount and sell_heap and sell_heap[0][0] <= price:
if sell_heap[0][1] <= amount:
amount -= sell_heap[0][1]
heapq.heappop(sell_heap)
else:
sell_heap[0][1] -= amount
amount = 0
if amount:
heapq.heappush(buy_heap, [-price, amount])
else: # sell:卖出
while amount and buy_heap and -buy_heap[0][0] >= price:
if buy_heap[0][1] <= amount:
amount -= buy_heap[0][1]
heapq.heappop(buy_heap)
else:
buy_heap[0][1] -= amount
amount = 0
if amount:
heapq.heappush(sell_heap, [price, amount])

return (sum(amount for price, amount in buy_heap) + sum(amount for price, amount in sell_heap)) % self._MOD


举报

相关推荐

0 条评论