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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| public class UnionFindUtils { public static final Map<String, String> parent = new HashMap<>(); public static final Map<String, Integer> rank = new HashMap<>();
public static String find(String token) { parent.putIfAbsent(token, token); rank.putIfAbsent(token, 1);
if (!parent.get(token).equals(token)) { parent.put(token, find(parent.get(token))); } return parent.get(token); }
public static void union(String token1, String token2) { String root1 = find(token1); String root2 = find(token2);
if (!root1.equals(root2)) { int rank1 = rank.getOrDefault(root1, 1); int rank2 = rank.getOrDefault(root2, 1);
if (rank1 > rank2) { parent.put(root2, root1); } else if (rank1 < rank2) { parent.put(root1, root2); } else { parent.put(root2, root1); rank.put(root1, rank1 + 1); } } }
public static boolean isConnected(String token1, String token2) { return find(token1).equals(find(token2)); }
public static List<List<String>> getGroupResult() { Map<String, List<String>> groups = new HashMap<>();
for (String token : parent.keySet()) { String root = find(token); groups.computeIfAbsent(root, k -> new ArrayList<>()).add(token); } ArrayList<List<String>> resList = new ArrayList<>(); for (Map.Entry<String, List<String>> entry : groups.entrySet()) { resList.add(entry.getValue()); } return resList; }
public static void main(String[] args) {
UnionFindUtils.union("token1", "token2"); UnionFindUtils.union("token3", "token2"); UnionFindUtils.union("token4", "token5"); UnionFindUtils.union("token6", "token7");
System.out.println("token1的根节点: " + UnionFindUtils.find("token1")); System.out.println("token4的根节点: " + UnionFindUtils.find("token4"));
System.out.println("token1和token3是否连接: " + UnionFindUtils.isConnected("token1", "token3")); System.out.println("token1和token4是否连接: " + UnionFindUtils.isConnected("token1", "token4"));
System.out.println(UnionFindUtils.getGroupResult()); } }
|