资讯专栏INFORMATION COLUMN

[LeetCode] 399. Evaluate Division

BlackMass / 1443人阅读

Problem

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> equations, vector& values, vector> queries , where equations.size() == values.size(), and the values are positive. This represents the equations. Return vector.

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 - Updated Union Find
class Solution {
    public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
        Map graph = new HashMap<>();
        Map ratio = new HashMap<>();
        double[] res = new double[queries.length];
        for (int i = 0; i < equations.length; i++) {
            String p0 = find(equations[i][0], graph, ratio);
            String p1 = find(equations[i][1], graph, ratio);
            graph.put(p0, p1);
            ratio.put(p0, values[i] * ratio.get(equations[i][1]) / ratio.get(equations[i][0]));
        }
        for (int i = 0; i < queries.length; i++) {
            if (!graph.containsKey(queries[i][0]) || !graph.containsKey(queries[i][1])) {
                res[i] = -1.0;
                continue;
            }
            String p0 = find(queries[i][0], graph, ratio);
            String p1 = find(queries[i][1], graph, ratio);
            if (!p0.equals(p1)) {
                res[i] = -1.0;
                continue;
            }
            res[i] = ratio.get(queries[i][0]) / ratio.get(queries[i][1]);
        }
        return res;
    }
    
    private String find(String str, Map graph, Map ratio) {
        if (!graph.containsKey(str)) {
            graph.put(str, str);
            ratio.put(str, 1.0);
            return str;
        }
        if (graph.get(str).equals(str)) return str;
        String parent = graph.get(str);
        String ancestor = find(parent, graph, ratio);
        graph.put(str, ancestor);
        ratio.put(str, ratio.get(str)*ratio.get(parent));
        return ancestor;
    }
}
Solution - DFS
class Solution {
    public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
        double[] res = new double[queries.length];
        Set dict = new HashSet<>();
        for (String[] pair: equations) {
            dict.add(pair[0]);
            dict.add(pair[1]);
        }
        for (int i = 0; i < queries.length; i++) {
            String[] pair = queries[i];
            if (!dict.contains(pair[0]) || !dict.contains(pair[1])) {
                res[i] = -1.0d;
            } else {
                res[i] = dfs(equations, values, pair, new HashSet());
            }
        }
        return res;
    }
    private double dfs(String[][] equations, double[] values, String[] pair, Set set) {
        for (int i = 0; i < equations.length; i++) {
            if (pair[0].equals(equations[i][0]) && pair[1].equals(equations[i][1])) return values[i];
            if (pair[0].equals(equations[i][1]) && pair[1].equals(equations[i][0])) return 1.0d/values[i];
        }
        
        for (int i = 0; i < equations.length; i++) {
            if (!set.contains(i) && pair[0].equals(equations[i][0])) {
                set.add(i);
                double temp = dfs(equations, values, new String[]{equations[i][1], pair[1]}, set)*values[i];
                if (temp > 0) return temp;
                else set.remove(i);
            }
            if (!set.contains(i) && pair[0].equals(equations[i][1])) {
                set.add(i);
                double temp = dfs(equations, values, new String[]{equations[i][0], pair[1]}, set)/values[i];
                if (temp > 0) return temp;
                else set.remove(i);
            }    
        }
        return -1.0d;
    }
}
Solution - Union Find
class Solution {
    public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
        Map graph = new HashMap<>();
        Map ratio = new HashMap<>();
        for (int i = 0; i < equations.length; i++) {
            union(graph, ratio, equations[i][0], equations[i][1], values[i]);
        }
        
        double[] res = new double[queries.length];
        for (int i = 0; i < queries.length; i++) {
            String s1 = queries[i][0], s2 = queries[i][1];
            if (!graph.containsKey(s1) || !graph.containsKey(s2) || !find(graph, ratio, s1).equals(find(graph, ratio, s2))) {
                res[i] = -1.0d;
            } else {
                res[i] = ratio.get(s1)/ratio.get(s2);
            }
        }
        return res;
    }
    
    private void union(Map graph, Map ratio, String s1, String s2, double value) {
        if (!graph.containsKey(s1)) {
            graph.put(s1, s1);
            ratio.put(s1, 1.0d);
        }
        if (!graph.containsKey(s2)) {
            graph.put(s2, s2);
            ratio.put(s2, 1.0d);
        }
        String p1 = find(graph, ratio, s1);
        String p2 = find(graph, ratio, s2);
        graph.put(p1, p2);
        
        ratio.put(p1, value*ratio.get(s2)/ratio.get(s1));
    }
    
    private String find(Map graph, Map ratio, String str) {
        if (str.equals(graph.get(str))) return str;
        String parent = graph.get(str);
        String ancestor = find(graph, ratio, parent);
        graph.put(str, ancestor);
        ratio.put(str, ratio.get(str)*ratio.get(parent));
        return ancestor;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72140.html

相关文章

  • leetcode399. Evaluate Division

    摘要:题目要求已知一些字母之间的关系式,问是否能够计算出其它字母之间的倍数关系如已知问是否能够计算出的值。这里的值因为在条件中无法获知是否等于零,因此也无法计算其真实结果,也需要返回。即代表点指向点的边的权重为,而点指向点的边的全中为。 题目要求 Equations are given in the format A / B = k, where A and B are variables ...

    Jensen 评论0 收藏0
  • 399. Evaluate Division

    摘要:建好图之后就是查找了,图里面查找用或者都可以,写起来简单点。复杂度没什么差别都是,这道题里面最多是,所以每次查找的复杂度是,有次查找。注意防止重复路径,要用。 399. Evaluate Division 题目链接:https://leetcode.com/problems... 无向图里找路径的问题,用邻接链或者邻接矩阵来建图,用邻接链的话注意两个方向,a/b的时候,既要把b加到a的...

    yanest 评论0 收藏0
  • [LeetCode] 150. Evaluate Reverse Polish Notation

    Problem Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Note: Division between two inte...

    KoreyLee 评论0 收藏0
  • LeetCode 150:逆波兰表达式求值 Evaluate Reverse Polish Nota

    摘要:题目根据逆波兰表示法,求表达式的值。给定逆波兰表达式总是有效的。逆波兰表达式又叫做后缀表达式。解题思路可以看出逆波兰表达式中的每一个运算符属于该运算符前的两个数字间的运算。如如波兰表达式则加号前两个数字为。 题目: 根据逆波兰表示法,求表达式的值。 有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。 Evaluate the value of...

    Turbo 评论0 收藏0
  • LeetCode 之 JavaScript 解答第150题 —— 逆波兰表达式求值

    摘要:小鹿题目根据逆波兰表示法,求表达式的值。给定逆波兰表达式总是有效的。算法思路仔细观察上述的逆波兰表达式,可以发现一个规律就是每遇到一个操作符,就将操作符前的两个操作数进行运算,将结果保存到原位置。 Time:2019/4/14Title: Evaluate Reverse Polish NotationDifficulty: MediumAuthor:小鹿 题目:Evaluate ...

    104828720 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<