[LeetCode]399. Evaluate Division

来源:互联网 发布:mac ps 2018无法破解 编辑:程序博客网 时间:2024/05/11 12:44

https://leetcode.com/problems/evaluate-division/?tab=Description

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





图问题:1、建图(数组 or map);2、dfs;3、缓存前序路径;4、终止条件(找到结尾 or 图内不存在该点 or 缓存内已存在当前位置)

public class Solution {    public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {        HashMap<String, HashMap<String, Double>> map = new HashMap();        for (int i = 0; i < equations.length; i++) {            String[] equation = equations[i];            HashMap<String, Double> temp = map.getOrDefault(equation[0], new HashMap());            temp.put(equation[1], values[i]);            map.put(equation[0], temp);            temp = map.getOrDefault(equation[1], new HashMap());            temp.put(equation[0], 1 / values[i]);            map.put(equation[1], temp);        }        double[] res = new double[queries.length];        for (int i = 0; i < res.length; i++) {            res[i] = dfs(map, queries[i][0], queries[i][1], new HashSet(), 1.0);            if (res[i] == 0.0) {                res[i] = -1.0;            }        }        return res;    }    private double dfs(HashMap<String, HashMap<String, Double>> map, String start, String end, HashSet<String> set, double pre) {        if (set.contains(start)) {            return 0.0;        }        if (!map.containsKey(start)) {            return 0.0;        }        if (start.equals(end)) {            return pre;        }        set.add(start);        double res = 0;        HashMap<String, Double> pair = map.get(start);        for (HashMap.Entry<String, Double> entry : pair.entrySet()) {            String key = (String) entry.getKey();            double val = (double) entry.getValue();            res = dfs(map, key, end, set, pre * val);            if (res != 0.0) {                break;            }        }        set.remove(start);        return res;    }}


0 0
原创粉丝点击