
| 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; |
| |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统