399. 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.

Solution

DFS directed-graph, O(nk), S(n ^ 2)

注意一定需要一个visited set记录已经访问过的节点,否则重复访问会导致死循环。

class Solution {
    public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
        Map<String, Map<String, Double>> map = new HashMap<>();
        
        for (int i = 0; i < equations.length; ++i) {
            if (!map.containsKey(equations[i][0])) {
                map.put(equations[i][0], new HashMap<>());
            }
            
            if (!map.containsKey(equations[i][1])) {
                map.put(equations[i][1], new HashMap<>());
            }
            
            map.get(equations[i][0]).put(equations[i][1], values[i]);
            map.get(equations[i][1]).put(equations[i][0], 1 / values[i]);
        }
        
        double[] res = new double[queries.length];
        Set<String> visited = new HashSet<>();
        
        for (int i = 0; i < res.length; ++i) {
            res[i] = dfsCalcEquation(queries[i][0], queries[i][1], map, visited);
        }
        
        return res;
    }
    
    public double dfsCalcEquation(
        String a, String b, Map<String, Map<String, Double>> map, Set<String> visited) {
        
        if (!map.containsKey(a) || !map.containsKey(b) || visited.contains(a)) {
            return -1;
        }
        
        if (a.equals(b)) {
            return 1;
        }
        
        visited.add(a);
        double res = -1;
        
        for (Map.Entry<String, Double> entry : map.get(a).entrySet()) {
            res = dfsCalcEquation(entry.getKey(), b, map, visited);
            if (res > 0) {
                res *= entry.getValue();
                break;
            }
        }
        
        visited.remove(a);
        return res;
    }
}

Optimized: Union-Find + Union by rank + Path compression, O(n + k), S(n)

这个思路真心牛掰,核心是`将common divisor作为root!
假设给定Graph是这样的(图左边)
新添加表达式a / e = 10.0之后,graph变成(图右边)


image.png

理解了思路之后,发现也并不难写。

class Solution {
    public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
        Map<String, Node> graph = new HashMap<>();
        // build graph
        for (int i = 0; i < equations.length; ++i) {
            String a = equations[i][0];
            String b = equations[i][1];
            double val = values[i];
            // initialize graph node if not exist
            if (!graph.containsKey(a)) {
                graph.put(a, new Node());
            }
            if (!graph.containsKey(b)) {
                graph.put(b, new Node());
            }
            // union!
            union(graph.get(a), graph.get(b), val);
        }
        
        double[] res = new double[queries.length];
        
        for (int i = 0; i < queries.length; ++i) {
            String a = queries[i][0];
            String b = queries[i][1];
            // decide if two nodes exist and are connected
            if (!graph.containsKey(a) || !graph.containsKey(b) 
                || !isConnected(graph.get(a), graph.get(b))) {
                res[i] = -1;
            } else {
                res[i] = graph.get(a).val / graph.get(b).val;
            }
        }
        
        return res;
    }
    
    private boolean isConnected(Node node1, Node node2) {
        return find(node1) == find(node2);
    }
    
    private Node find(Node node) {
        if (node.parent == null) {
            return node;
        }
        node.parent = find(node.parent);
        return node.parent;
    }
    
    private void union(Node node1, Node node2, double val) {
        if (isConnected(node1, node2)) { // important! don't union connected ones
            return;
        }
        
        Node root1 = find(node1);
        Node root2 = find(node2);
        // make sure we union smaller set to bigger set
        if (root1.children.size() <= root2.children.size()) {
            unionHelper(node1, node2, val);
        } else {
            unionHelper(node2, node1, 1 / val);
        }
    }
    // mount node1 set to node2 set, node1 is smaller set, path compression!
    private void unionHelper(Node node1, Node node2, double val) {
        Node root1 = find(node1);
        Node root2 = find(node2);
        double ratio = node2.val * val / node1.val;
        // mount root1.children to root2       
        for (Node child : root1.children) {
            child.val *= ratio;
            child.parent = root2;
            root2.children.add(child);
        }
        // don't forget to make root2 the parent of root1 too!
        root1.val = ratio;
        root1.parent = root2;
        root2.children.add(root1);
        root1.children.clear();
    }
    
    class Node {
        Node parent;
        List<Node> children;
        double val;
        
        public Node() {
            val = 1d;   // because x / x = 1
            children = new ArrayList<>();
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,636评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,890评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,680评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,766评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,665评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,045评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,515评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,182评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,334评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,274评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,319评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,002评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,599评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,675评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,917评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,309评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,885评论 2 341

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,267评论 0 10
  • 这几天状态不好,发资料的时候挑人,要微信的时候没有势在必得的心态导致收集资料会比之前少,我明白我出现了问题,也明白...
    九月fine阅读 459评论 1 2
  • 我是天空里的一片云 行走在人间蜿蜒的小路上 我不点烟火 我只看风景 最大的风景是我爱你 然后我用泪水淋透你 也因此...
    FreelyJ阅读 116评论 0 0
  • 不断打喷嚏 不停流鼻涕 流感面前我是如此 不堪一击 一杯一杯的茶水 一口一口地喘息 借助药片的威力 把自己置身于梦...
    A老周A阅读 160评论 0 0