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

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

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

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

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

示例 1:

输入:stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
输出:5

提示:

  • 1 <= stones.length <= 2000
  • 0 <= xi, yi <= 10^4

解析

使用并查集,同行或同列的石头属于同一个连通分量。最终可以保留的石头数量等于连通分量的数量,所以可以移除的石头数量 = 总数 - 连通分量数。

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
var removeStones = function (stones) {
const parent = {};

const find = (x) => {
if (!parent[x]) parent[x] = x;
if (parent[x] !== x) parent[x] = find(parent[x]);
return parent[x];
};

const union = (x, y) => {
const px = find(x);
const py = find(y);
if (px !== py) parent[px] = py;
};

for (const [x, y] of stones) {
union(x, y + 10001);
}

const roots = new Set();
for (const [x, y] of stones) {
roots.add(find(x));
}

return stones.length - roots.size;
};

时间复杂度 O(n α(n)),空间复杂度 O(n)。


947.移除最多的同行或同列石头
https://leetcode.lz5z.com/947.most-stones-removed-with-same-row-or-column/
作者
tickli
发布于
2025年3月10日
许可协议