题目
给出方程式 A / B = k, 其中 A 和 B 均为用字符串表示的变量, k 是一个浮点型数字。根据已知方程式求解问题,并返回计算结果。如果结果不存在,则返回 -1.0。
链接:https://leetcode.com/problems/evaluate-division/
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:
Input: equations = [ [“a”, “b”], [“b”, “c”] ],
values = [2.0, 3.0],
queries = [ [“a”, “c”], [“b”, “a”], [“a”, “e”], [“a”, “a”], [“x”, “x”] ].
Output: [6.0, 0.5, -1.0, 1.0, -1.0 ].
思路及代码
并查集 Union-Find
- Union-Find的思想是给所有的元素找到同样的根,并集时要合并为相同根
- 本题对每一个元素存储为在字典中:key: [root, value],其中key = root * value
- 比如x/y = 2则x:[y,2]和y:[y,1]
- 在最后计算答案的时候,溯源到根节点:x = root * vx, y = root * vy,则x/y = vx / vy,若找不到相同的根节点则返回-1
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]