-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
45 lines (43 loc) · 1.44 KB
/
Solution.java
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
class Solution {
private Map<String, String> p;
private Map<String, Double> w;
public double[] calcEquation(
List<List<String>> equations, double[] values, List<List<String>> queries) {
int n = equations.size();
p = new HashMap<>();
w = new HashMap<>();
for (List<String> e : equations) {
p.put(e.get(0), e.get(0));
p.put(e.get(1), e.get(1));
w.put(e.get(0), 1.0);
w.put(e.get(1), 1.0);
}
for (int i = 0; i < n; ++i) {
List<String> e = equations.get(i);
String a = e.get(0), b = e.get(1);
String pa = find(a), pb = find(b);
if (Objects.equals(pa, pb)) {
continue;
}
p.put(pa, pb);
w.put(pa, w.get(b) * values[i] / w.get(a));
}
int m = queries.size();
double[] ans = new double[m];
for (int i = 0; i < m; ++i) {
String c = queries.get(i).get(0), d = queries.get(i).get(1);
ans[i] = !p.containsKey(c) || !p.containsKey(d) || !Objects.equals(find(c), find(d))
? -1.0
: w.get(c) / w.get(d);
}
return ans;
}
private String find(String x) {
if (!Objects.equals(p.get(x), x)) {
String origin = p.get(x);
p.put(x, find(p.get(x)));
w.put(x, w.get(x) * w.get(origin));
}
return p.get(x);
}
}