https://leetcode.com/problems/minimum-index-sum-of-two-lists/
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 |