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 81 82 83 84 85 86 87 88 89 90 91
| class Solution { private static class UnionFind { private final int[] parent; private final double[] divisionValues;
public UnionFind(int n) { this.parent = new int[n]; this.divisionValues = new double[n]; for (int i = 0; i < n; i++) { parent[i] = i; divisionValues[i] = 1.0; } }
public void union(int x, int y, double divisionValue) { int xRoot = getRoot(x); int yRoot = getRoot(y); if (xRoot == yRoot) { return; }
parent[xRoot] = yRoot; divisionValues[xRoot] = divisionValue * divisionValues[y] / divisionValues[x]; }
public int getRoot(int x) { if (x != parent[x]) { int p = parent[x]; int root = getRoot(p); divisionValues[x] *= divisionValues[p]; parent[x] = root; }
return parent[x]; }
public double getDivisionValue(int x, int y) { return divisionValues[x] / divisionValues[y]; }
public boolean isUnion(int x, int y) { return getRoot(x) == getRoot(y); } }
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) { Map<String, Integer> varToIndexMap = new HashMap<>(); for (List<String> equation : equations) { for (String var : equation) { if (!varToIndexMap.containsKey(var)) { varToIndexMap.put(var, varToIndexMap.size()); } } }
UnionFind unionFind = new UnionFind(varToIndexMap.size());
for (int i = 0; i < equations.size(); i++) { List<String> equation = equations.get(i); int index1 = varToIndexMap.get(equation.get(0)), index2 = varToIndexMap.get(equation.get(1)); unionFind.union(index1, index2, values[i]); }
double[] results = new double[queries.size()]; for (int i = 0; i < queries.size(); i++) { List<String> query = queries.get(i); Integer index1 = varToIndexMap.get(query.get(0)), index2 = varToIndexMap.get(query.get(1)); if (index1 == null || index2 == null || !unionFind.isUnion(index1, index2)) { results[i] = -1.0; } else { results[i] = unionFind.getDivisionValue(index1, index2); } }
return results; } }
|