zoukankan      html  css  js  c++  java
  • Python编程题29两个列表的最小索引总和

    题目

    给定两个列表,每个列表都不含有重复元素,但两个列表之间可能包含有共同元素,请计算两个列表中共同元素的最小索引之和,并以列表的形式,返回对应的元素,如果两个列表没有共同元素,则返回空列表。

    例如:

    给定两个列表: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]
    

    更多Python编程题,等你来挑战:Python编程题汇总(持续更新中……)

    作者:wintest
    本文版权归作者和博客园共有,欢迎转载,但必须在文章页面明显位置给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
  • 相关阅读:
    Vue内敛模板
    vue自定义组件添加原生事件监听
    vue 组件开发 props 验证
    Vue中子组件数据跟着父组件改变和父组件数据跟着子组件改变的方法
    jQuery中outerWidth()方法
    CSS3-transition
    行内元素(例如)设置float之后才能用width调整宽度
    leetcode LRU Cache python
    opcache effect
    leetcode Same Tree python
  • 原文地址:https://www.cnblogs.com/wintest/p/15583850.html
Copyright © 2011-2022 走看看