题目:
leetcode.cn/problems/nu…
算法:
方法一:堆+模拟
思路不难,代码量略大大
func getNumberOfBacklogOrders(orders [][]int) int {
// buyOrder 最大堆, sellOrder 最小堆
buyOrder := newHeap(false)
sellOrder := newHeap(true)
mod := 1000000007
for i := range orders {
// 如果是一笔买入订单
if orders[i][2] == 0 {
// 没有卖的库存,则增加买库存
if len(sellOrder.order) == 0 {
heap.Push(buyOrder, orders[i])
} else {
for orders[i][1] > 0 && len(sellOrder.order) > 0{
if sellOrder.order[0][0] > orders[i][0] {
break
}
sell := heap.Pop(sellOrder).([]int)
count := min(orders[i][1], sell[1])
orders[i][1] = orders[i][1] - count
sell[1] = sell[1] - count
if sell[1] > 0 {
heap.Push(sellOrder, sell)
}
}
if orders[i][1] > 0 {
heap.Push(buyOrder, orders[i])
}
}
} else {
if len(buyOrder.order) == 0 {
heap.Push(sellOrder, orders[i])
} else {
for orders[i][1] > 0 && len(buyOrder.order) > 0 {
if buyOrder.order[0][0] < orders[i][0] {
break
}
buy := heap.Pop(buyOrder).([]int)
count := min(orders[i][1], buy[1])
orders[i][1] = orders[i][1] - count
buy[1] = buy[1] - count
if buy[1] > 0 {
heap.Push(buyOrder, buy)
}
}
if orders[i][1] > 0 {
heap.Push(sellOrder, orders[i])
}
}
}
}
ans := 0
for i := range sellOrder.order {
ans = (ans + sellOrder.order[i][1]) % mod
}
for i := range buyOrder.order {
ans = (ans + buyOrder.order[i][1]) % mod
}
return ans
}
type myHeap struct {
order [][]int
issmall bool
}
func (h myHeap) Len() int { return len(h.order) }
func (h myHeap) Less(i, j int) bool {
if h.issmall {
return h.order[i][0] < h.order[j][0]
}
return h.order[i][0] > h.order[j][0]
}
func (h myHeap) Swap(i, j int) {
h.order[i], h.order[j] = h.order[j], h.order[i]
}
func (h *myHeap) Push(x interface{}) {
(*h).order = append((*h).order, x.([]int))
}
func (h *myHeap) Pop() interface{} {
n := len((*h).order)
x := (*h).order[n-1]
(*h).order = (*h).order[:n-1]
return x
}
func newHeap(issmall bool) *myHeap {
return &myHeap{
order: make([][]int, 0),
issmall: issmall,
}
}
func min(a, b int) int {
if a < b {
return a
}
return b
}