|
| 1 | +/** |
| 2 | + * Question Link: https://leetcode.com/problems/evaluate-division/ |
| 3 | + * Primary idea: Classic Union Find. Update roots and values while building the graph. |
| 4 | + * |
| 5 | + * Time Complexity: O((M + N) * logN), Space Complexity: O(N) |
| 6 | + * |
| 7 | + */ |
| 8 | + |
| 9 | +class EvaluateDivision { |
| 10 | + func calcEquation(_ equations: [[String]], _ values: [Double], _ queries: [[String]]) -> [Double] { |
| 11 | + var res = [Double]() |
| 12 | + var graph = union(equations, values) |
| 13 | + |
| 14 | + for query in queries { |
| 15 | + if graph[query[0]] == nil || graph[query[1]] == nil { |
| 16 | + res.append(-1.0) |
| 17 | + continue |
| 18 | + } |
| 19 | + |
| 20 | + let left = find(&graph, query[0]) |
| 21 | + let right = find(&graph, query[1]) |
| 22 | + |
| 23 | + if left.0 != right.0 { |
| 24 | + res.append(-1.0) |
| 25 | + } else { |
| 26 | + res.append(left.1 / right.1) |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + return res |
| 31 | + } |
| 32 | + |
| 33 | + private func find(_ roots: inout [String: (String, Double)], _ node: String) -> (String, Double) { |
| 34 | + if roots[node] == nil { |
| 35 | + roots[node] = (node, 1) |
| 36 | + } |
| 37 | + |
| 38 | + var n = roots[node]!.0 |
| 39 | + |
| 40 | + while n != roots[n]!.0 { |
| 41 | + roots[node] = (roots[n]!.0, roots[n]!.1 * roots[node]!.1) |
| 42 | + n = roots[n]!.0 |
| 43 | + } |
| 44 | + |
| 45 | + return roots[node]! |
| 46 | + } |
| 47 | + |
| 48 | + private func union(_ equations: [[String]], _ values: [Double]) -> [String: (String, Double)] { |
| 49 | + var res = [String: (String, Double)]() |
| 50 | + |
| 51 | + for i in 0..<equations.count { |
| 52 | + let left = find(&res, equations[i][0]) |
| 53 | + let right = find(&res, equations[i][1]) |
| 54 | + |
| 55 | + if left.0 != right.0 { |
| 56 | + res[left.0] = (right.0, values[i] * right.1 / left.1) |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + return res |
| 61 | + } |
| 62 | +} |
0 commit comments