LeetCode之Evaluate Division(Kotlin)

227 阅读1分钟

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

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.

方法: 首先遍历equations,保存直接等式关系;然后遍历rels,由已知关系生成间接关系;最后通过rels可以直接查询到所有的结果,查询时间复杂度是O(1)。

具体实现:

class EvaluateDivision {
    fun calcEquation(equations: Array<Array<String>>, values: DoubleArray, queries: Array<Array<String>>): DoubleArray {
        val result = mutableListOf<Double>()
        val rels = mutableMapOf<String, MutableMap<String, Double>>()
        for ((index, equation) in equations.withIndex()) {
            val x = equation[0]
            val y = equation[1]
            if (rels.containsKey(x)) {
                rels[x]?.put(y, values[index])
            } else {
                rels.put(x, mutableMapOf(y to values[index]))
            }
            if (rels.containsKey(y)) {
                rels[y]?.put(x, 1.0 / values[index])
            } else {
                rels.put(y, mutableMapOf(x to 1.0 /values[index]))
            }
        }
        for (rel in rels) {
            for (x in rel.value) {
                for (y in rel.value) {
                    rels[x.key]?.put(y.key, y.value / x.value)
                    rels[y.key]?.put(x.key, x.value / y.value)
                }
            }
        }
        for (query in queries) {
            val x = rels[query[0]]
            if (x == null) {
                result.add(-1.0)
            } else {
                val y = x[query[1]]
                if (y == null) {
                    result.add(-1.0)
                } else {
                    result.add(y)
                }
            }
        }
        return result.toDoubleArray()
    }
}

fun main(args: Array<String>) {
    val equations = arrayOf(arrayOf("a", "b"), arrayOf("b", "c"))
    val values = doubleArrayOf(2.0, 3.0)
    val queries = arrayOf(arrayOf("a", "c"), arrayOf("b", "a"), arrayOf("a", "e"), arrayOf("a", "a"), arrayOf("x", "x"))
    val evaluateDivision = EvaluateDivision()
    val result = evaluateDivision.calcEquation(equations, values, queries)
    CommonUtils.printArray(result.toTypedArray())
}

有问题随时沟通

具体代码实现可以参考Github