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.
需要HashMap<String, HashMap<String, Double>>来存各个元素之间的关系,之后用DFS来查找元素。当元素相等时返回1.0,用一个hashset存已经visited的路径。有一点需要注意,double不能判断null,Doublr可以,因为这道题可能出现各种结果,所以判断不符合条件是最好使用null。代码如下:public class Solution {
public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
HashMap<String, HashMap<String, Double>> map = new HashMap<String, HashMap<String, Double>>();
for (int i = 0; i < equations.length; i ++) {
String x = equations[i][0];
String y = equations[i][1];
if (!map.containsKey(x)) {
map.put(x, new HashMap<String, Double>());
}
map.get(x).put(y, values[i]);
if (!map.containsKey(y)) {
map.put(y, new HashMap<String, Double>());
}
map.get(y).put(x, 1 / values[i]);
}
double[] res = new double[queries.length];
for (int i = 0; i < res.length; i ++) {
Double result = DFS(map, queries[i][0], queries[i][1], new HashSet<String>());
res[i] = result == null? -1.0: result;
}
return res;
}
private Double DFS(HashMap<String, HashMap<String, Double>> map, String x, String y, HashSet<String> visited) {
if (!map.containsKey(x) || !map.containsKey(y)) {
return null;
}
String dupeKey = x + ":" + y;
if (visited.contains(dupeKey)) {
return null;
}
if (x.equals(y)) {
return 1.0;
}
visited.add(dupeKey);
for (String variable: map.get(x).keySet()) {
Double result = DFS(map, variable, y, visited);
if (result != null) {
return result * map.get(x).get(variable);
}
}
visited.remove(dupeKey);
return null;
}
}