399. Evaluate Division
Posted gopanama
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了399. Evaluate Division相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/evaluate-division/discuss/88169/Java-AC-Solution-using-graph
建立graph dfs
value是按照值建立的 这样dfs的时候可以直接乘
1 class Solution { 2 public double[] calcEquation(String[][] equations, double[] values, String[][] queries) { 3 HashMap<String, List<String>> pairs = new HashMap<>(); 4 HashMap<String, List<Double>> value = new HashMap<>(); 5 for(int i = 0; i < equations.length; i++){ 6 if(!pairs.containsKey(equations[i][0])){ 7 pairs.put(equations[i][0], new ArrayList<>()); 8 value.put(equations[i][0], new ArrayList<>()); 9 } 10 if(!pairs.containsKey(equations[i][1])){ 11 pairs.put(equations[i][1], new ArrayList<>()); 12 value.put(equations[i][1], new ArrayList<>()); 13 } 14 pairs.get(equations[i][0]).add(equations[i][1]); 15 pairs.get(equations[i][1]).add(equations[i][0]); 16 value.get(equations[i][0]).add(values[i]); 17 value.get(equations[i][1]).add(1 / values[i]); 18 } 19 20 double[] result = new double[queries.length]; 21 int i = 0; 22 for(String[] query : queries){ 23 if(!pairs.containsKey(query[0]) || !pairs.containsKey(query[1])){ 24 result[i++] = -1.0; 25 continue; 26 } 27 double res = dfs(pairs, value, new HashSet<String>(), query[0], query[1], 1.0); 28 if(res == 0.0){ 29 result[i++] = -1.0; 30 }else{ 31 result[i++] = res; 32 } 33 } 34 return result; 35 36 } 37 38 public double dfs(HashMap<String, List<String>> pairs, HashMap<String, List<Double>> values, HashSet<String> set, String start, String end, double num){ 39 if(start.equals(end)) return num; 40 if(set.contains(start)) return 0.0; 41 set.add(start); 42 43 List<String> list = pairs.get(start); 44 List<Double> value = values.get(start); 45 double res = 0.0; 46 for(int i = 0; i < list.size(); i++){ 47 if(!set.contains(list.get(i))){ 48 res = dfs(pairs, values, set, list.get(i), end, num * value.get(i)); 49 } 50 if(res != 0.0) break; 51 } 52 return res; 53 } 54 }
以上是关于399. Evaluate Division的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 399. Evaluate Division