近期CSOahelp石老师的学生在tiktok的面试中,碰到一题典型的“除法方程”题——LeetCode 399。题目长这样(完整英文原文):
Title: Division
Question description
You 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.
Note: The variables that do not occur in the list of equations are undefined,
so the answer cannot be determined for them.
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]
一句话拆解全题:
把变量当节点,除法当有向带权边,用 DFS 找路径、连乘权重。
下面是一个伪代码的示例,
from collections import defaultdict
def calc(eqs, vals, qs):
# 1. 建图:g[X][Y] = X/Y;反向 g[Y][X] = 1/v
g = defaultdict(dict)
for (X, Y), v in zip(eqs, vals):
g[X][Y] = v
g[Y][X] = 1/v
# 2. DFS:从 u 到 t,沿途乘权重,找不到就 -1
def dfs(u, t, seen):
if u not in g or t not in g: # 变量没出现过
return -1.0
if u == t: # x/x = 1
return 1.0
seen.add(u)
for w, wt in g[u].items():
if w in seen: continue
res = dfs(w, t, seen)
if res != -1.0:
return wt * res
return -1.0
# 3. 一行搞定所有查询
return [dfs(a, b, set()) for a, b in qs]
# 测试一下
eqs = [["a","b"],["b","c"]]
vals= [2.0,3.0]
qs = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
print(calc(eqs, vals, qs)) # [6.0, 0.5, -1.0, 1.0, -1.0]
核心要点
- 建图:
g[X][Y] = v
,以及g[Y][X] = 1/v
- DFS:带一个
seen
集合防环,找到目标就把沿路所有wt
相乘 - 边界:变量不存在立刻
-1.0
;自除x/x = 1.0
如果想再快一点,可以加个小缓存:DFS 找到一次结果后,直接 g[C][D] = 结果
,下一次同样查询瞬间返回。或者用并查集(Union-Find)带权优化,查询能做到几乎 O(1)。
题解leetcode上有很多写的比我好的,我就不献丑讲更多了。
2025暑期发面试的公司不多,tiktok算是其中比较活跃的了,如果你暑期收到了tiktok的面试,不妨认真准备一下,竞争对手其实会比秋招的时候少很多。
另外暑期活跃的公司还有Amazon,需要Amazon亚麻真题的可以看这里:传送门
如果同学们对于在北美求职有什么疑问,欢迎咨询我哦,石老师知无不言。24小时欢迎大家来骚扰。
csoahelp.com每日分享北美大厂面经,小红书也有更新,我们还提供种类多样的收费服务协助您进入北美科技大厂,有意向的微信扫码联系我,或者也可以通过其他方式联系我
