1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
| // @Title: 移除最多的同行或同列石头 (Most Stones Removed with Same Row or Column)
// @Author: 15816537946@163.com
// @Date: 2021-01-16 10:55:56
// @Runtime: 20 ms
// @Memory: 6.7 MB
type unionFind struct {
parent map[int]int
cnt int
}
func NewUnionFind() *unionFind {
return &unionFind{
parent: make(map[int]int),
}
}
func (u *unionFind) getCount() int {
return u.cnt
}
func (u *unionFind) find(x int) int {
if _, exists := u.parent[x]; !exists {
u.parent[x] = x
u.cnt++
}
if x != u.parent[x] {
u.parent[x] = u.find(u.parent[x])
}
return u.parent[x]
}
func (u *unionFind) union(x, y int) {
rootX, rootY := u.find(x), u.find(y)
if rootX == rootY {
return
}
u.parent[rootX] = rootY
u.cnt--
}
func removeStones(stones [][]int) int {
uf := NewUnionFind()
for _, s := range stones {
uf.union(s[0]+10001, s[1])
}
return len(stones) - uf.getCount()
}
|