[LeetCode] 399. Evaluate Division
Equations are given in the format
A / B = k
, where A
and B
are variables represented as strings, and k
is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0
.
Example:
Given
queries are:
return
Given
a / b = 2.0, b / c = 3.0.
queries are:
a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
return
[6.0, 0.5, -1.0, 1.0, -1.0 ].
The input is:
vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries
, where equations.size() == values.size()
, and the values are positive. This represents the equations. Return vector<double>
.
According to the example above:
equations = [ ["a", "b"], ["b", "c"] ], values = [2.0, 3.0], queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].
The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.
Thought process:
Build graph and do DFS.
Solution:
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 | class Solution { public double[] calcEquation(String[][] equations, double[] values, String[][] queries) { Map<String, List<String>> graph = new HashMap<>(); Map<String, Double> weights = new HashMap<>(); for (int i = 0; i < equations.length; i++) { String s1 = equations[i][0]; String s2 = equations[i][1]; if (!graph.containsKey(s1)) { graph.put(s1, new ArrayList<>()); } graph.get(s1).add(s2); if (!graph.containsKey(s2)) { graph.put(s2, new ArrayList<>()); } graph.get(s2).add(s1); weights.put(s1 + "," + s2, values[i]); weights.put(s2 + "," + s1, 1 / values[i]); } double[] result = new double[queries.length]; for (int i = 0; i < queries.length; i++) { String src = queries[i][0]; if (!graph.containsKey(src)) { result[i] = -1; continue; } String dest = queries[i][1]; Set<String> visited = new HashSet<>(); dfs(graph, weights, visited, src, dest, 1, result, i); if (result[i] == 0) { result[i] = -1; } } return result; } private void dfs(Map<String, List<String>> graph, Map<String, Double> weights, Set<String> visited, String src, String dest, double weight, double[] result, int index) { if (src.equals(dest)) { result[index] = weight; return; } visited.add(src); for (String neighbor : graph.get(src)) { if (!visited.contains(neighbor)) { dfs(graph, weights, visited, neighbor, dest, weight * weights.get(src + "," + neighbor), result, index); } } } } |
Time complexity:
Say there're e equations and q queries. Building the graph takes O(e). The queries take O(q) iterations and O(e) per iteration. So the overall time complexity is O(eq).
Comments
Post a Comment