399. Evaluate Division
Evaluate Division
题目描述:
ou are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable.
You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?.
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 <= Ai.length, Bi.length <= 5
values.length == equations.length
0.0 < values[i] <= 20.0
1 <= queries.length <= 20
queries[i].length == 2
1 <= Cj.length, Dj.length <= 5
Ai, Bi, Cj, Dj consist of lower case English letters and digits.
思路:
可以两种方法做,并查集和bfs,把a/b =2 看成 a->b = 2,b->a = 1/2,用图的思想做。
代码:
func calcEquation(equations [][]string, values []float64, queries [][]string) []float64 {
var res []float64
graph := map[string]map[string]float64{}
for k,v := range equations{
if _,ok := graph[v[0]];!ok{
graph[v[0]] = make(map[string]float64, 0)
}
if _,ok := graph[v[1]];!ok{
graph[v[1]] = make(map[string]float64, 0)
}
graph[v[0]][v[1]] = values[k]
graph[v[1]][v[0]] = 1/values[k]
graph[v[0]][v[0]] = 1
graph[v[1]][v[1]] = 1
}
var calc func(a, b string, visit map[string]bool)float64
calc = func(a,b string, visit map[string]bool)float64{
if _,ok := graph[a];!ok{
return -1
}
if _,ok := graph[b];!ok{
return -1
}
if v,ok := graph[a][b];ok{
return v
}else{
for key,value := range graph[a]{
// 防止重复
if _,ok := (visit)[key];ok{
continue
}
visit[a] = true
ans := calc(key,b,visit)
if ans != -1{
return ans *value
}
}
}
return -1
}
for _,v := range queries{
res = append(res, calc(v[0],v[1], map[string]bool{}))
}
return res
}
代码效率:
执行用时:0 ms, 在所有 Go 提交中击败了100.00%的用户
内存消耗:2.2 MB, 在所有 Go 提交中击败了100.00%的用户
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!