首页 > 代码库 > 399. Evaluate Division
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"] ]. 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, DFS
(1) Build the map, the key is dividend, the value is also a map whose key is divisor and value is its parameter. For example, a / b = 2.0
, the map entry is <"a", <"b", 2.0>>
. To make searching and calculation easier, we also put b / a = 0.5
into the map.
(2) for each query, use DFS to search divisors recursively
1.hashmap 建图
2. dfs 递归搜索
public class Solution { public double[] calcEquation(String[][] equations, double[] values, String[][] queries) { double[] res = new double[queries.length]; HashMap<String, HashMap<String, Double>> map = new HashMap<String, HashMap<String, Double>>(); for (int i=0; i<equations.length; i++) { String[] equation = equations[i]; double value = http://www.mamicode.com/values[i];>
399. Evaluate Division
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。