題目
給定兩個列表,每個列表都不含有重複元素,但兩個列表之間可能包含有共同元素,請計算兩個列表中共同元素的最小索引之和,並以列表的形式,返回對應的元素,如果兩個列表沒有共同元素,則返回空列表。
例如:
給定兩個列表:list1=['hello', 'word', '222', 'hi', 'good'], list2=['first', 'hi', 'good', 'WORD', 'hello']
返回結果:['hi', 'hello']說明:兩個列表存在 3 個共同元素,這3個元素對應的索引之和分別爲 0+4、3+1、4+2,所以最小索引之和爲 4 ,對應的重複元素是 ['hi', 'hello']
給定兩個列表:list1=['hello', 'word'], list2=['first', 'hi']
返回結果:[]說明:兩個列表不存在共同元素,直接返回空列表。
實現思路
- 通過set集合的方式求出共同元素,並保存到 tmp_set 中,如果 tmp_set 爲空,則直接返回空列表
- 分別用字典 tmp_dict1 和 tmp_dict2 存儲2個列表中每個元素及其索引
- 用字典 index_sum_dict 存儲2個列表中共同元素及對應索引之和
- 求出2個列表的最小索引之和
- 根據最小索引之和,求出對應的共同元素
代碼實現
def findRestaurant(self, list1, list2):
tmp_set = set(list1) & set(list2)
if len(tmp_set) == 0:
return []
tmp_dict1 = {list1[i]: i for i in range(len(list1))}
tmp_dict2 = {list2[i]: i for i in range(len(list2))}
index_sum_dict = {i: (tmp_dict1.get(i) + tmp_dict2.get(i)) for i in tmp_set}
min_index_sum = min(list(index_sum_dict.values()))
return [i for i in tmp_set if index_sum_dict.get(i) == min_index_sum]