Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 760b39c

Browse files
aQuaaQua
aQua
authored and
aQua
committed
850 solved
1 parent aeec9a7 commit 760b39c

File tree

2 files changed

+77
-5
lines changed

2 files changed

+77
-5
lines changed
Lines changed: 72 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,82 @@
11
package problem0850
22

3+
import (
4+
"sort"
5+
)
6+
37
const mod = 1e9 + 7
48

59
func rectangleArea(rectangles [][]int) int {
6-
sum := 0
10+
xs := getXs(rectangles)
11+
sort.Ints(xs)
12+
13+
idxX := make(map[int]int, 2*len(xs))
14+
for k, x := range xs {
15+
idxX[x] = k
16+
}
17+
18+
count := make([]int, len(xs))
19+
20+
L := make([][]int, 0, 2*len(rectangles))
21+
722
for _, r := range rectangles {
8-
sum += area(r)
23+
x1, y1, x2, y2 := r[0], r[1], r[2], r[3]
24+
L = append(L,
25+
[]int{y1, x1, x2, 1},
26+
[]int{y2, x1, x2, -1},
27+
)
928
}
10-
return sum % mod
29+
30+
sort.Slice(L, func(i int, j int) bool {
31+
eq0 := L[i][0] == L[j][0]
32+
eq1 := L[i][1] == L[j][1]
33+
eq2 := L[i][2] == L[j][2]
34+
if eq0 && eq1 && eq2 {
35+
return L[i][3] < L[j][3]
36+
}
37+
if eq0 && eq1 {
38+
return L[i][2] < L[j][2]
39+
}
40+
if eq0 {
41+
return L[i][1] < L[j][1]
42+
}
43+
return L[i][0] < L[j][0]
44+
})
45+
46+
curY, curXSum, area := 0, 0, 0
47+
48+
for _, l := range L {
49+
y, x1, x2, sig := l[0], l[1], l[2], l[3]
50+
area += (y - curY) * curXSum
51+
curY = y
52+
for i := idxX[x1]; i < idxX[x2]; i++ {
53+
count[i] += sig
54+
}
55+
curXSum = 0
56+
for i := 0; i+1 < len(count); i++ {
57+
if count[i] != 0 {
58+
curXSum += xs[i+1] - xs[i]
59+
}
60+
}
61+
62+
}
63+
64+
return area % mod
1165
}
1266

13-
func area(r []int) int {
14-
return ((r[2] - r[0]) * (r[3] - r[1])) % mod
67+
func getXs(rects [][]int) []int {
68+
size := len(rects)
69+
res := make([]int, 1, size*2)
70+
xMap := make(map[int]bool, size*2)
71+
72+
for _, r := range rects {
73+
xMap[r[0]] = true
74+
xMap[r[2]] = true
75+
}
76+
77+
for k := range xMap {
78+
res = append(res, k)
79+
}
80+
81+
return res
1582
}

Algorithms/0850.rectangle-area-ii/rectangle-area-ii_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ var tcs = []struct {
2323
49,
2424
},
2525

26+
{
27+
[][]int{{0, 0, 1000000000, 1000000000}, {0, 1000000000, 1000000000, 2000000000}},
28+
98,
29+
},
30+
2631
// 可以有多个 testcase
2732
}
2833

0 commit comments

Comments
 (0)