原题链接在这里: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.
题解:
建立graph, 和graph中的edge的weight.
在求新的query时做dfs. 求结果.
Time Complexity: O(queries.length*(V+E)). dfs 用时O(V+E). E = equations.length. V = graph.size().
Space: O(V). regardless res.
AC Java:
1 class Solution { 2 public double[] calcEquation(String[][] equations, double[] values, String[][] queries) { 3 HashMap<String, List<String>> graph = new HashMap<String, List<String>>(); 4 HashMap<String, List<Double>> weight = new HashMap<String, List<Double>>(); 5 for(int i = 0; i<equations.length; i++){ 6 String [] equation = equations[i]; 7 if(!graph.containsKey(equation[0])){ 8 graph.put(equation[0], new ArrayList<String>()); 9 weight.put(equation[0], new ArrayList<Double>()); 10 } 11 graph.get(equation[0]).add(equation[1]); 12 weight.get(equation[0]).add(values[i]); 13 14 if(values[i] == 0.0){ 15 continue; 16 } 17 18 if(!graph.containsKey(equation[1])){ 19 graph.put(equation[1], new ArrayList<String>()); 20 weight.put(equation[1], new ArrayList<Double>()); 21 } 22 graph.get(equation[1]).add(equation[0]); 23 weight.get(equation[1]).add(1.0/values[i]); 24 } 25 26 double [] res = new double[queries.length]; 27 for(int i = 0; i<queries.length; i++){ 28 String [] query = queries[i]; 29 res[i] = dfs(query[0], query[1], graph, weight, new HashSet<String>(), 1.0); 30 if(res[i] == 0.0){ 31 res[i] = -1.0; 32 } 33 } 34 35 return res; 36 } 37 38 private double dfs(String start, String end, Map<String, List<String>> graph, Map<String, List<Double>> weight, Set<String> visited, double cur){ 39 if(visited.contains(start) || !graph.containsKey(start)){ 40 return 0.0; 41 } 42 43 if(start.equals(end)){ 44 return cur; 45 } 46 47 double res = 0.0; 48 visited.add(start); 49 for(int i = 0; i<graph.get(start).size(); i++){ 50 res = dfs(graph.get(start).get(i), end, graph, weight, visited, cur*weight.get(start).get(i)); 51 if(res != 0.0){ 52 break; 53 } 54 } 55 visited.remove(start); 56 return res; 57 } 58 }
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/8452702.html