Skip to content

599 Minimum Index Sum of Two Lists

599. Minimum Index Sum of Two Lists

题目: https://leetcode.com/problems/Minimum-Index-Sum-of-Two-Lists/

难度:

Easy

思路

两个list,我们首先要取得它们相同的部分,并且之后我们还要知道哪个相同的字符串在两个list中的index之和是最小的。 - 所以我们首先遍历list1,只要目前这个字符串在list2中,我们就以[字符串,index之和]的形式将其存放到ress中,同时维护一个index保持为最小index之和的值 - 对于ress,我们遍历,只要某一项的index之和等于最小index之和我们就将他的字符串以i[0]的形式append到res中去, - return res

程序变量解释

  • ress format: [[string1, sumOfIndex1], [string2, sumOfIndex2]... ]
  • index 最小sunOfIndex值
  • res 最终结果,foramt: [string1, string2,. ...]
python
class Solution:
    def findRestaurant(self, list1, list2):
        """
        :type list1: List[str]
        :type list2: List[str]
        :rtype: List[str]
        """
        ress = []
        index = 2000
        for i in list1:
            if i in list2:
                ress.append([i, list1.index(i)+list2.index(i)])
                index = min(index, list1.index(i)+list2.index(i))
        res = []
        for i in ress:
            if i[1] == index:
                res.append(i[0])
        return res

Author: Keqi Huang

If you like it, please spread your support

Support



回到顶部