Skip to content

Commit 67a401f

Browse files
committed
1488: sol with BS
Signed-off-by: ductnn <[email protected]>
1 parent be96407 commit 67a401f

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

leetcode/daily/1488/sol.go

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"sort"
6+
)
7+
8+
func avoidFlood(rains []int) []int {
9+
n := len(rains)
10+
ans := make([]int, n)
11+
full := make(map[int]int)
12+
dryDays := []int{}
13+
14+
for i, lake := range rains {
15+
// Rain Day
16+
if lake > 0 {
17+
ans[i] = -1
18+
if day, ok := full[lake]; ok {
19+
// Lake full, need 1 dry day to dry it
20+
idx := findDryDayAfter(dryDays, day) // idx in dryDays slice
21+
if idx == -1 {
22+
return []int{} // No dry day found -> flood
23+
}
24+
// Use the actual dry day (value), not the index
25+
actualDay := dryDays[idx]
26+
ans[actualDay] = lake
27+
// Remove the used dry day from the list (by index)
28+
dryDays = append(dryDays[:idx], dryDays[idx+1:]...)
29+
}
30+
full[lake] = i
31+
} else {
32+
// Dry Day
33+
dryDays = append(dryDays, i)
34+
ans[i] = 1
35+
}
36+
}
37+
38+
return ans
39+
}
40+
41+
// Find the index in dryDays of the first day > day
42+
// Ex: dryDays = [2, 4, 5], day = 3 => idx = 1
43+
// Ex: dryDays = [2, 4, 5], day = 6 => idx = -1
44+
func findDryDayAfter(dryDays []int, day int) int {
45+
idx := sort.Search(len(dryDays), func(i int) bool { return dryDays[i] > day })
46+
if idx == len(dryDays) {
47+
return -1
48+
}
49+
return idx
50+
}
51+
52+
func main() {
53+
rains := []int{1, 2, 0, 0, 2, 1}
54+
fmt.Println(avoidFlood(rains)) // => [-1 -1 2 1 -1 -1]
55+
}

0 commit comments

Comments
 (0)