面试题答案
一键面试分析
- 直接添加并去重:将
small_list
直接添加到big_list
后,使用集合(set)去重。时间复杂度为 O((m + n) + (m + n)),其中 m 是big_list
的长度,n 是small_list
的长度,第一个 (m + n) 是添加操作,第二个 (m + n) 是集合去重操作。空间复杂度为 O(m + n),因为集合需要额外的空间存储去重后的元素。 - 先合并为集合再转回列表:将
big_list
和small_list
转换为集合,合并后再转回列表。时间复杂度为 O(m + n),空间复杂度为 O(m + n)。 - 遍历添加并检查重复:遍历
small_list
,逐个检查是否在big_list
中,不存在则添加。时间复杂度为 O(m * n),空间复杂度为 O(1),因为不需要额外的空间存储。
在列表非常大的情况下,先合并为集合再转回列表的方法效率最高。
代码实现
big_list = [1, 2, 3, 4, 5] * 100000
small_list = [4, 5, 6, 7]
# 先合并为集合再转回列表
big_set = set(big_list)
small_set = set(small_list)
unique_set = big_set.union(small_set)
result_list = list(unique_set)
复杂度总结
方法 | 时间复杂度 | 空间复杂度 |
---|---|---|
直接添加并去重 | O((m + n) + (m + n)) | O(m + n) |
先合并为集合再转回列表 | O(m + n) | O(m + n) |
遍历添加并检查重复 | O(m * n) | O(1) |