clllll  

image

import java.util.HashMap;
class Solution {
public static HashMap<Integer, Integer> row = new HashMap<>();
public static HashMap<Integer, Integer> col = new HashMap<>();
public static int MAXN = 1001;
public static int[] f = new int[MAXN];
public static int set = MAXN;
public static void build(int n) {
row.clear();
col.clear();
for (int i = 0; i < n; i++) {
f[i] = i;
}
set = n;
}
public static int find(int i) {
if (f[i] != i) {
f[i] = find(f[i]);
}
return f[i];
}
public static void union(int i, int j) {
int f_i = find(i);
int f_j = find(j);
if (f_i != f_j) {
f[f_i] = f_j;
set--;
}
}
public int removeStones(int[][] stones) {
int n = stones.length;
build(n);
for (int i = 0; i < n; i++) {
if (row.containsKey(stones[i][0])) {
// 当前行已经有数了。可以合并。
union(i, row.get(stones[i][0]));
} else {
row.put(stones[i][0], i);
}
if (col.containsKey(stones[i][1])) {
union(i, col.get(stones[i][1]));
} else {
col.put(stones[i][1], i);
}
}
return n - set;
}
}
posted on   llcl  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
 
点击右上角即可分享
微信分享提示