algorithm

599. Minimum Index Sum of Two Lists

식피두 2020. 8. 31. 00:58

https://leetcode.com/problems/minimum-index-sum-of-two-lists/

 

Minimum Index Sum of Two Lists - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

270ms

import collections

class Solution:
    def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
        a = set(list1)
        b = set(list2)
        
        common = a.intersection(b)
        
        candi = collections.defaultdict(list)
        
        for word in common:
            idx0 = list1.index(word)
            idx1 = list2.index(word)
            idx_sum = idx0+idx1
            
            candi[idx_sum].append(word)
        
        min_val = min(list(candi.keys()))
        
        return candi[min_val]

 

fix one position

 

136ms

class Solution:
    def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
        m, n = len(list1), len(list2)
        restaurant_mapper = {val: i for i, val in enumerate(list1)}
        best = m + n
        result = []
        for i, val in enumerate(list2):
            if val in restaurant_mapper:
                if restaurant_mapper[val] + i < best:
                    best = restaurant_mapper[val] + i
                    result = [val]
                elif restaurant_mapper[val] + i == best:
                    result.append(val)
        return result

'algorithm' 카테고리의 다른 글

676. Implement Magic Dictionary  (0) 2020.09.03
662. Maximum Width of Binary Tree  (0) 2020.08.31
654. Maximum Binary Tree  (0) 2020.08.31
696. Count Binary Substrings  (0) 2020.08.31
594. Longest Harmonious Subsequence  (0) 2020.08.31