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 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"] ].
class Solution { Map<String, Map<String, Double>> g = new HashMap(); public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) { for(int i = 0; i < values.length; i++) { String fir = equations.get(i).get(0); String sec = equations.get(i).get(1); g.computeIfAbsent(fir, l -> new HashMap()).put(sec, values[i]); g.computeIfAbsent(sec, l -> new HashMap()).put(fir, 1.0 / values[i]); } double[] res = new double[queries.size()]; for(int i = 0; i < queries.size(); i++) { res[i] = dfs(g, queries.get(i).get(0), queries.get(i).get(1), new HashSet()); } return res; } public double dfs(Map<String, Map<String, Double>> map, String start, String end, Set<String> used) { if(!map.containsKey(start)) return -1.0;
if(map.get(start).containsKey(end)) return map.get(start).get(end); used.add(start); for(String neighbor : map.get(start).keySet()) { if(used.contains(neighbor)) continue; double midproduct = dfs(map, neighbor, end, used); if(midproduct != -1.0) return map.get(start).get(neighbor) * midproduct; } return -1.0; } }
1. 阳间方法,graph + dfs
http://zxi.mytechroad.com/blog/graph/leetcode-399-evaluate-division/花哥讲解
看着代码长其实挺好理解,先用Map<String, Map<String, Double>>来表示有向图,注意权重值不同,每条路径唯一
然后iterate queries,
dfs参数是分子,分母,visited(确保不进入死循环)
从start开始,如果map中找不到它直接返回-1说明不存在这个分子。然后时成功条件:map中有start也有end,就返回这条边代表的weight。
在下一步之前先把start添加到used里面,否则会死循环。然后iterate这个start所有的neighbor,代表了我没有直接到end的边,但我可以让我兄弟找到你,
找啊找啊,如果找到了(返回不是-1)那就说明有边可以间接到达end,返回从start到这个neighbor和neighbor到end的product即可。
//map.containsKey(map.get(start).get(end))
不要写成这个了啊,傻逼卧槽。比如a / b = 2, 这个是containsKey(2), 应该是map.get(start).containsKey(end),containsKey(b)
至于remove,有没有都可以(因为是单向的)
2. 阴间方法,union find
挖个坑