【LeetCode】399. Evaluate Division 除法求值(Medium)(JAVA)每日一题

【LeetCode】399. Evaluate Division 除法求值(Medium)(JAVA)

题目地址: https://leetcode.com/problems/evaluate-division/

题目描述:

You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [A_i, B_i] and values[i] represent the equation A_i / B_i = values[i]. Each A_i or B_i is a string that represents a single variable.

You are also given some queries, where queries[j] = [C_j, D_j] represents the jth query where you must find the answer for C_j / D_j = ?.

Return the answers to all queries. If a single answer cannot be determined, return -1.0.

Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.

Example 1:

Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000]
Explanation: 
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 ]

Example 2:

Input: equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]]
Output: [3.75000,0.40000,5.00000,0.20000]

Example 3:

Input: equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]]
Output: [0.50000,2.00000,-1.00000,-1.00000]

Constraints:

  • 1 <= equations.length <= 20
  • equations[i].length == 2
  • 1 <= A_i.length, B_i.length <= 5
  • values.length == equations.length
  • 0.0 < values[i] <= 20.0
  • 1 <= queries.length <= 20
  • queries[i].length == 2
  • 1 <= C_j.length, D_j.length <= 5
  • A_i, B_i, C_j, D_j consist of lower case English letters and digits.

题目大意

给你一个变量对数组 equations 和一个实数值数组 values 作为已知条件,其中 equations[i] = [A_i, B_i] 和 values[i] 共同表示等式 A_i / B_i = values[i] 。每个 A_i 或 B_i 是一个表示单个变量的字符串。

另有一些以数组 queries 表示的问题,其中 queries[j] = [C_j, D_j] 表示第 j 个问题,请你根据已知条件找出 C_j / D_j = ? 的结果作为答案。

返回 所有问题的答案 。如果存在某个无法确定的答案,则用 -1.0 替代这个答案。

注意:输入总是有效的。你可以假设除法运算中不会出现除数为 0 的情况,且不存在任何矛盾的结果。

解题方法

暴力解法

  1. 建立一个有向图,用一个 mapKey 的 k-v 形式存储,再用一个 mapValue 存储出现的 k / v 的计算结果值
  2. 搜素新的值 x / y, x, y 必须在 mapKey 里面,如果得到了结果从重新存到 mapValue 里面
class Solution {
    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
        Map<String, List<String>> mapKey = new HashMap<>();
        Map<String, Double> mapValue = new HashMap<>();
        for (int i = 0; i < values.length; i++) {
            String first = equations.get(i).get(0);
            String second = equations.get(i).get(0);
            putMap(mapKey, first, second);
            putMap(mapKey, second, first);
            mapValue.put(getKey(first, second), values[i]);
            mapValue.put(getKey(second,  first), 1 / values[i]);
        }
        double[] res = new double[queries.size()];
        for (int i = 0; i < queries.size(); i++) {
            res[i] = getValue(mapKey, mapValue, queries.get(i).get(0), queries.get(i).get(1));
        }
        return res;
    }

    public double getValue(Map<String, List<String>> mapKey, Map<String, Double> mapValue, String first, String second) {
        if (mapKey.get(first) == null || mapKey.get(second) == null) return -1.0;
        Double pre = mapValue.get(getKey(first, second));
        if (pre != null) return pre;
        List<String> list = mapKey.get(first);
        double res = -1.0;
        for (int i = 0; i < list.size(); i++) {
            String next = list.get(i);
            if (second.equals(next)) return mapValue.get(getKey(first, second));
            double nextValue = getValue(mapKey, mapValue, next, second);
            if (nextValue < 0) continue;
            res = nextValue * mapValue.get(getKey(first, next));
            break;
        }
        putMap(mapKey, first, second);
        mapValue.put(getKey(first, second), res);
        putMap(mapKey, second, first);
        mapValue.put(getKey(second, first), 1.0 / res);
        return res;
    }

    public void putMap(Map<String, List<String>> mapKey, String first, String second) {
        List<String> list = mapKey.get(first);
        if (list == null) {
            list = new ArrayList<>();
            mapKey.put(first, list);
        }
        list.add(second);
    }

    public String getKey(String first, String second) {
        return first + "-" + second;
    }
}

Memory Limit Exceeded

优化

  1. leetcode 官网解答
class Solution {
    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
        int nvars = 0;
        Map<String, Integer> variables = new HashMap<String, Integer>();

        int n = equations.size();
        for (int i = 0; i < n; i++) {
            if (!variables.containsKey(equations.get(i).get(0))) {
                variables.put(equations.get(i).get(0), nvars++);
            }
            if (!variables.containsKey(equations.get(i).get(1))) {
                variables.put(equations.get(i).get(1), nvars++);
            }
        }

        // 对于每个点,存储其直接连接到的所有点及对应的权值
        List<Pair>[] edges = new List[nvars];
        for (int i = 0; i < nvars; i++) {
            edges[i] = new ArrayList<Pair>();
        }
        for (int i = 0; i < n; i++) {
            int va = variables.get(equations.get(i).get(0)), vb = variables.get(equations.get(i).get(1));
            edges[va].add(new Pair(vb, values[i]));
            edges[vb].add(new Pair(va, 1.0 / values[i]));
        }

        int queriesCount = queries.size();
        double[] ret = new double[queriesCount];
        for (int i = 0; i < queriesCount; i++) {
            List<String> query = queries.get(i);
            double result = -1.0;
            if (variables.containsKey(query.get(0)) && variables.containsKey(query.get(1))) {
                int ia = variables.get(query.get(0)), ib = variables.get(query.get(1));
                if (ia == ib) {
                    result = 1.0;
                } else {
                    Queue<Integer> points = new LinkedList<Integer>();
                    points.offer(ia);
                    double[] ratios = new double[nvars];
                    Arrays.fill(ratios, -1.0);
                    ratios[ia] = 1.0;

                    while (!points.isEmpty() && ratios[ib] < 0) {
                        int x = points.poll();
                        for (Pair pair : edges[x]) {
                            int y = pair.index;
                            double val = pair.value;
                            if (ratios[y] < 0) {
                                ratios[y] = ratios[x] * val;
                                points.offer(y);
                            }
                        }
                    }
                    result = ratios[ib];
                }
            }
            ret[i] = result;
        }
        return ret;
    }
}

class Pair {
    int index;
    double value;

    Pair(int index, double value) {
        this.index = index;
        this.value = value;
    }
}

执行耗时:1 ms,击败了97.24% 的Java用户
内存消耗:37.3 MB,击败了46.02% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/112258312
今日推荐