問題: 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())
}
複製程式碼
有問題隨時溝通