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
| class Solution { public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) { Set<String> nodeSet = new HashSet<>(); Map<String, String> parentMap = new HashMap<>(); Map<String, Double> valueMap = new HashMap<>(); build(nodeSet, parentMap, valueMap, equations, values); return query(nodeSet, parentMap, valueMap, queries); }
private double[] query(Set<String> nodeSet, Map<String, String> parentMap, Map<String, Double> valueMap, List<List<String>> queries) { double[] result = new double[queries.size()]; for (int i = 0; i < queries.size(); i++) { String first = queries.get(i).get(0); String second = queries.get(i).get(1); if (!nodeSet.contains(first) || !nodeSet.contains(second)) { result[i] = -1.0; continue; }
String firstParent = getParent(first, parentMap, valueMap); String secondParent = getParent(second, parentMap, valueMap); if (!firstParent.equals(secondParent)) { result[i] = -1.0; } else { result[i] = valueMap.get(first) / valueMap.get(second); } }
return result; }
private void build(Set<String> nodeSet, Map<String, String> parentMap, Map<String, Double> valueMap, List<List<String>> equations, double[] values) { for (int i = 0; i < equations.size(); i++) { List<String> equation = equations.get(i); String first = equation.get(0); String second = equation.get(1); nodeSet.add(first); nodeSet.add(second); String firstParent = getParent(first, parentMap, valueMap); String secondParent = getParent(second, parentMap, valueMap); if (!firstParent.equals(secondParent)) { parentMap.put(firstParent, secondParent); valueMap.put(firstParent, values[i] * valueMap.get(second) / valueMap.get(first)); } } }
private String getParent(String str, Map<String, String> parentMap, Map<String, Double> valueMap) { if (parentMap.get(str) == null) { valueMap.put(str, 1.0); return str; }
String root = getParent(parentMap.get(str), parentMap, valueMap); valueMap.put(str, valueMap.get(str) * valueMap.get(parentMap.get(str))); parentMap.put(str, root);
return root; } }
|