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

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.

思路:
无向图里找路径的问题,用邻接链或者邻接矩阵来建图,用邻接链的话注意两个方向,a/b的时候,既要把b加到a的邻接list里,也要把a加到b的邻接list里面。建好图之后就是查找了,图里面查找用bfs或者dfs都可以,dfs写起来简单点。复杂度没什么差别都是O(V+E),这道题里面E = equations.length, V最多是2E,所以每次查找的复杂度是O(equations.length),有queries.length次查找。注意防止重复路径,要用visited。

class Solution {
    public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
        // build graph, use adjacent list
        map = new HashMap();
        for(int i = 0; i < equations.length; i++) {
            String[] equation = equations[i];
            if(!map.containsKey(equation[0])) map.put(equation[0], new ArrayList());
            map.get(equation[0]).add(new Info(equation[1], values[i]));

            if(!map.containsKey(equation[1])) map.put(equation[1], new ArrayList());
            map.get(equation[1]).add(new Info(equation[0], 1 / values[i]));
        }

        double[] result = new double[queries.length];
        for(int i = 0; i < result.length; i++) {
            result[i] = find(queries[i][0], queries[i][1], 1, new HashSet());
        }
        return result;
    }

    HashMap<String, List<Info>> map;

    private double find(String start, String end, double value, Set<String> visited) {
        if(visited.contains(start)) return -1;
        if(!map.containsKey(start)) return -1;

        if(start.equals(end)) return value;
        visited.add(start);
        for(Info next : map.get(start)) {
            double sub = find(next.den, end, value * next.val, visited);
            if(sub != -1.0) return sub;
        }

        visited.remove(start);
        return -1;
    }

    class Info {
        String den;
        double val;
        Info(String den, double val) { 
            this.den = den; 
            this.val = val; 
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值