Skip to content

Commit 099e0f7

Browse files
committed
1488: sol with min heap
Signed-off-by: ductnn <[email protected]>
1 parent 67a401f commit 099e0f7

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

leetcode/daily/1488/sol2.go

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
// https://leetcode.com/problems/avoid-flood-in-the-city
2+
3+
package main
4+
5+
import (
6+
"container/heap"
7+
"fmt"
8+
)
9+
10+
type Pair struct {
11+
day int
12+
lake int
13+
}
14+
15+
type MinHeap []Pair
16+
17+
func (h MinHeap) Len() int { return len(h) }
18+
func (h MinHeap) Less(i, j int) bool { return h[i].day < h[j].day }
19+
func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
20+
func (h *MinHeap) Push(x interface{}) {
21+
*h = append(*h, x.(Pair))
22+
}
23+
func (h *MinHeap) Pop() interface{} {
24+
old := *h
25+
n := len(old)
26+
x := old[n-1]
27+
*h = old[:n-1]
28+
return x
29+
}
30+
31+
func avoidFlood(rains []int) []int {
32+
n := len(rains)
33+
ans := make([]int, n)
34+
full := make(map[int]bool) // hồ nào đang đầy
35+
next := make(map[int][]int) // hồ -> danh sách ngày mưa tiếp theo
36+
37+
// Tiền xử lý: lưu trước các ngày mưa của từng hồ
38+
for i, lake := range rains {
39+
if lake > 0 {
40+
next[lake] = append(next[lake], i)
41+
}
42+
}
43+
44+
h := &MinHeap{}
45+
heap.Init(h)
46+
47+
for i, lake := range rains {
48+
if lake > 0 {
49+
// Bỏ qua ngày hôm nay
50+
next[lake] = next[lake][1:]
51+
52+
if full[lake] {
53+
// Mưa vào hồ đang đầy -> flood
54+
return []int{}
55+
}
56+
full[lake] = true
57+
ans[i] = -1
58+
59+
// Nếu còn mưa hồ này trong tương lai -> đưa vào heap
60+
if len(next[lake]) > 0 {
61+
heap.Push(h, Pair{day: next[lake][0], lake: lake})
62+
}
63+
} else {
64+
// Ngày khô
65+
if h.Len() > 0 {
66+
p := heap.Pop(h).(Pair)
67+
ans[i] = p.lake
68+
full[p.lake] = false
69+
} else {
70+
ans[i] = 1 // dry hồ bất kỳ
71+
}
72+
}
73+
}
74+
75+
return ans
76+
}
77+
78+
func main() {
79+
rains := []int{1, 2, 0, 0, 2, 1}
80+
fmt.Println(avoidFlood(rains)) // expected: [-1, -1, 2, 1, -1, -1]
81+
}

0 commit comments

Comments
 (0)