面试题答案
一键面试def find_keys(nested_dict, target, threshold):
result = []
for outer_key, inner_dict in nested_dict.items():
count = 0
for sublist in inner_dict.values():
count += sublist.count(target)
if count > threshold:
result.append(outer_key)
return result
时间复杂度分析:
- 外层循环遍历外层字典的键,时间复杂度为$O(m)$,其中
m
是外层字典的键的数量。 - 内层循环遍历内层字典的值(列表),每个内层字典值的列表长度不同,假设平均长度为
n
,且内层字典平均键数量为k
,那么对于每个外层字典键,遍历内层字典值列表计算目标元素出现次数的时间复杂度为$O(k \cdot n)$。 - 整体时间复杂度为$O(m \cdot k \cdot n)$。
优化方法:
- 优化数据结构:
- 如果数据允许预处理,可以将原始的嵌套字典结构转换为一种更便于统计的数据结构。例如,预先统计每个目标元素在所有内层列表中的出现次数,这样在查询时可以直接获取结果,时间复杂度降为$O(m)$。
- 优化算法:
- 避免使用
list.count
方法,因为它的时间复杂度是$O(n)$。可以通过一次遍历内层列表,使用一个计数器变量来统计目标元素的出现次数,这样对于每个内层列表统计的时间复杂度变为$O(n)$,整体时间复杂度降为$O(m \cdot k)$。优化后的代码如下:
- 避免使用
def optimized_find_keys(nested_dict, target, threshold):
result = []
for outer_key, inner_dict in nested_dict.items():
count = 0
for sublist in inner_dict.values():
for num in sublist:
if num == target:
count += 1
if count > threshold:
result.append(outer_key)
break
return result
这样在大规模数据下,由于减少了不必要的重复遍历,性能会得到提升。