Featured image of post 947. 移除最多的同行或同列石头

947. 移除最多的同行或同列石头

题目描述

n 块石头放置在二维平面中的一些整数坐标点上。每个坐标点上最多只能有一块石头。

如果一块石头的 同行或者同列 上有其他石头存在,那么就可以移除这块石头。

给你一个长度为 n 的数组 stones ,其中 stones[i] = [xi, yi] 表示第 i 块石头的位置,返回 可以移除的石子 的最大数量。

示例 1:

  • 输入:stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
  • 输出:5
  • 解释:一种移除 5 块石头的方法如下所示:
    1. 移除石头 [2,2] ,因为它和 [2,1] 同行。
    2. 移除石头 [2,1] ,因为它和 [0,1] 同列。
    3. 移除石头 [1,2] ,因为它和 [1,0] 同行。
    4. 移除石头 [1,0] ,因为它和 [0,0] 同列。
    5. 移除石头 [0,1] ,因为它和 [0,0] 同行。
    6. 石头 [0,0] 不能移除,因为它没有与另一块石头同行/列。

示例 2:

  • 输入:stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
  • 输出:3
  • 解释:一种移除 3 块石头的方法如下所示:
    1. 移除石头 [2,2] ,因为它和 [2,0] 同行。
    2. 移除石头 [2,0] ,因为它和 [0,0] 同列。
    3. 移除石头 [0,2] ,因为它和 [0,0] 同行。
    4. 石头 [0,0] 和 [1,1] 不能移除,因为它们没有与另一块石头同行/列。

示例 3:

  • 输入:stones = [[0,0]]
  • 输出:0
  • 解释:[0,0] 是平面上唯一一块石头,所以不可以移除它。

提示:

  • 1 <= stones.length <= 1000
  • 0 <= xi, yi <= 104
  • 不会有两块石头放在同一个坐标点上

解法一:并查集

 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
type UnionFind struct {
    parent map[int]int
    count  map[int]int
}

func NewUnionFind() *UnionFind {
    uf := &UnionFind{parent: make(map[int]int), count: make(map[int]int)}
    return uf
}

func (uf *UnionFind) Find(i int) int {
    if _, has := uf.parent[i]; !has {
        uf.parent[i] = i
        uf.count[i] = 0
    }
    if uf.parent[i] != i {
        uf.parent[i] = uf.Find(uf.parent[i])
    }
    return uf.parent[i]
}

func (uf *UnionFind) Merge(i, j int) {
    iF, jF := uf.Find(i), uf.Find(j)
    if iF == jF {
        uf.count[iF]++
    } else {
        uf.parent[iF] = jF
        uf.count[jF] += uf.count[iF] + 1
    }
}

func (uf *UnionFind) Resolve() int {
    ans := 0
    for k, v := range uf.parent {
        if k == v {
            ans += uf.count[k] - 1
        }
    }
    return ans
}

func removeStones(stones [][]int) int {
    uf := NewUnionFind()
    for _, stone := range stones {
        x, y := stone[0], stone[1]
        uf.Merge(x+100001, y)
    }
    return uf.Resolve()
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2023/08/12 22:32:10
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计