LeetCode 399. Evaluate Division
原题链接在这里:https://leetcode.com/problems/evaluate-division/description/
题目:
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 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.
题解:
Construct graph with edge weight Map<String, Map<String, Double>> graph.
在求新的query时做dfs. 求结果.
Time Complexity: O(queries.size()*(equations.size())). dfs 用时O(V+E). E = equations.length. V node count can't be greater than equations.size().
Space: O(V). regardless res.
AC Java:
1 class Solution { 2 public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) { 3 Map<String, Map<String, Double>> graph = new HashMap<>(); 4 for(int i = 0; i<values.length; i++){ 5 List<String> equation = equations.get(i); 6 String a = equation.get(0); 7 String b = equation.get(1); 8 9 graph.putIfAbsent(a, new HashMap<String, Double>()); 10 graph.get(a).putIfAbsent(b, values[i]); 11 12 if(values[i] == 0){ 13 continue; 14 } 15 16 graph.putIfAbsent(b, new HashMap<String, Double>()); 17 graph.get(b).putIfAbsent(a, 1.0/values[i]); 18 } 19 20 double [] res = new double[queries.size()]; 21 for(int i = 0; i<queries.size(); i++){ 22 List<String> query = queries.get(i); 23 res[i] = dfs(query.get(0), query.get(1), 1.0, graph, new HashSet<String>()); 24 } 25 26 return res; 27 } 28 29 private double dfs(String s, String e, double cur, Map<String, Map<String, Double>> graph, Set<String> visited){ 30 if(!graph.containsKey(s) || !visited.add(s)){ 31 return -1.0; 32 } 33 34 if(s.equals(e)){ 35 return cur; 36 } 37 38 Map<String, Double> neighbors = graph.get(s); 39 for(Map.Entry<String, Double> entry : neighbors.entrySet()){ 40 double temp = dfs(entry.getKey(), e, cur*entry.getValue(), graph, visited); 41 if(temp != -1.0){ 42 return temp; 43 } 44 } 45 46 return -1.0; 47 } 48 }