面试题答案
一键面试dict_a = {'x': {'inner_key1': 10, 'inner_key2': 20}, 'y': {'inner_key3': 30}, 'z': {'inner_key4': 40}}
dict_b = {'x': {'inner_key1': 15, 'inner_key5': 25}, 'z': {'inner_key4': 45, 'inner_key6': 55}}
result = {}
for key in set(dict_a.keys()) & set(dict_b.keys()):
inner_result = {}
for inner_key, inner_value in dict_a[key].items():
if inner_key in dict_b[key] and dict_b[key][inner_key] == inner_value:
inner_result[inner_key] = inner_value
if inner_result:
result[key] = inner_result
print(result)
时间复杂度分析
- 求外层字典键的交集:
set(dict_a.keys()) & set(dict_b.keys())
,假设dict_a
和dict_b
分别有m
和n
个键,将字典的键转换为集合时间复杂度为$O(m)$和$O(n)$,求集合交集时间复杂度为$O(min(m, n))$,总体为$O(m + n)$。 - 内层循环:对于每个外层字典的公共键,假设内层字典平均长度为
k
,内层循环的时间复杂度为$O(k)$,总共有$O(min(m, n))$个公共键,所以这部分时间复杂度为$O(min(m, n) * k)$。
综合起来,整个算法的时间复杂度为$O(m + n + min(m, n) * k)$。当m
和n
相近,且k
相对较小的情况下,时间复杂度近似为$O(m * k)$ 。