由于工作语言是Go,所以就用Go来解答,刚好熟悉一下Go相关的知识,这里主要是碰到了Go实现大小堆,具体的思路已完成,Go大小堆知识待补充。
题目链接:https://leetcode.com/problems/number-of-orders-in-the-backlog/
You are given a 2D integer array orders
, where each orders[i] = [price<sub>i</sub>, amount<sub>i</sub>, orderType<sub>i</sub>]
denotes that amount<sub>i</sub>
~ ~orders have been placed of type orderType<sub>i</sub>
at the price price<sub>i</sub>
. The orderType<sub>i</sub>
is:
0
if it is a batch ofbuy
orders, or1
if it is a batch ofsell
orders.
Note that orders[i]
represents a batch of amount<sub>i</sub>
independent orders with the same price and order type. All orders represented by orders[i]
will be placed before all orders represented by orders[i+1]
for all valid i
.
There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens:
- If the order is a
buy
order, you look at thesell
order with the smallest price in the backlog. If thatsell
order’s price is smaller than or equal to the currentbuy
order’s price, they will match and be executed, and thatsell
order will be removed from the backlog. Else, thebuy
order is added to the backlog. - Vice versa, if the order is a
sell
order, you look at thebuy
order with the largest price in the backlog. If thatbuy
order’s price is larger than or equal to the currentsell
order’s price, they will match and be executed, and thatbuy
order will be removed from the backlog. Else, thesell
order is added to the backlog.
Return the total amount of orders in the backlog after placing all the orders from the input . Since this number can be large, return it modulo 10<sup>9</sup> + 7
.
Constraints:
1 <= orders.length <= 10<sup>5</sup>
orders[i].length == 3
1 <= price<sub>i</sub>, amount<sub>i</sub> <= 10<sup>9</sup>
orderType<sub>i</sub>
is either0
or1
.
解题思路
这是一个优先队列模拟的问题,存储当前的积压订单,在新的订单到来的时候根据类型,若来的是购买订单,则找出价格最低的销售订单,且当销售订单的价格<=购买订单的价格时,进行匹配并相应消除;反之购买订单>=销售订单,进行消除。
要快速找到最小最大的订单价格,一个是插入时对slice进行sort排序,第二个就是使用大小堆进行判断,思路很简单,代码如下,主要是GO的大小堆实现卡住了我还蛮久的时间。。。相应博客指路 =>
1 | func getNumberOfBacklogOrders(orders [][]int) int { |