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 = values[i];
            if (!map.containsKey(equation[0])) {
                map.put(equation[0], new HashMap<String, Double>());
                map.get(equation[0]).put(equation[0], 1.0);
            }
            if (!map.containsKey(equation[1])) {
                map.put(equation[1], new HashMap<String, Double>());
                map.get(equation[1]).put(equation[1], 1.0);
            }
            map.get(equation[0]).put(equation[1], value);
            map.get(equation[1]).put(equation[0], 1/value);
        }

        for (int j=0; j<queries.length; j++) {
            res[j] = -1.0; //initialize
            dfs(map, queries[j][0], queries[j][1], new HashSet<String>(), res, j, 1.0);
        }
        return res;
    }

    public void dfs(HashMap<String, HashMap<String, Double>> map, String src, String dest, HashSet<String> visited, double[] res, int index, double pathVal) {
        if (!map.containsKey(src) || !map.containsKey(dest)) {
            res[index] = -1.0;
            return;
        }
        if (visited.contains(src)) return;
        HashMap<String, Double> srcNb = map.get(src);
        if (srcNb.containsKey(dest)) {
            res[index] = pathVal * srcNb.get(dest);
            return;
        }
        visited.add(src);
        for (Map.Entry<String, Double> entry : srcNb.entrySet()) {
            String neibor = entry.getKey();
            dfs(map, neibor, dest, visited, res, index, pathVal*entry.getValue());
        }
        visited.remove(src);
    }
}

  

时间: 2024-12-25 22:21:13

399. Evaluate Division的相关文章

【Graph】399. Evaluate Division(Medium)

#week3# #from leetcode# 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,

[LeetCode] 399. Evaluate Division Java

题目: 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 /

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 a

[leetcode]Graph-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 =

过中等难度题目.0310

  .   8  String to Integer (atoi)    13.9% Medium   . 151 Reverse Words in a String      15.7% Medium     . 288 Unique Word Abbreviation      15.8% Medium     . 29 Divide Two Integers      16.0% Medium     . 166 Fraction to Recurring Decimal      17.

继续过中等难度.0309

  .   8  String to Integer (atoi)    13.9% Medium   . 151 Reverse Words in a String      15.7% Medium     . 288 Unique Word Abbreviation      15.8% Medium     . 29 Divide Two Integers      16.0% Medium     . 166 Fraction to Recurring Decimal      17.

LeetCode Problems List 题目汇总

No. Title Level Rate 1 Two Sum Medium 17.70% 2 Add Two Numbers Medium 21.10% 3 Longest Substring Without Repeating Characters Medium 20.60% 4 Median of Two Sorted Arrays Hard 17.40% 5 Longest Palindromic Substring Medium 20.70% 6 ZigZag Conversion Ea

Leetcode problems classified by company 题目按公司分类(Last updated: October 2, 2017)

Sorted by frequency of problems that appear in real interviews.Last updated: October 2, 2017Google (214)534 Design TinyURL388 Longest Absolute File Path683 K Empty Slots340 Longest Substring with At Most K Distinct Characters681 Next Closest Time482

[总结]图

在图的基本算法中,最初需要接触的就是图的遍历算法,根据访问节点的顺序,可分为广度优先搜索(BFS)和深度优先搜索(DFS).深度优先搜索,顾名思义即为一条道走到黑的搜索策略,行不通退回来换另外一条道再走到黑,依次直到搜索完成.其过程简要来说是对每一个可能的分支路径深入到不能再深入为止,而且每个节点只能访问一次.宽度优先搜索算法(又称广度优先搜索)是最简便的图的搜索算法之一,这一算法也是很多重要的图的算法的原型.Dijkstra单源最短路径算法和Prim最小生成树算法都采用了和宽度优先搜索类似的思