Solution 1 - Index Map
Map list1 items to indices; scan list2 and keep items with minimal index sum.
Map list1 items to indices; scan list2 and keep items with minimal index sum.
""" 0599.1 - Minimum Index Sum of Two Lists - Solution 1 - Index Map """
class Solution:
def findRestaurant(self, list1, list2):
pos = {x: i for i, x in enumerate(list1)}
best = 10**9
out = []
for j, x in enumerate(list2):
if x in pos:
s = pos[x] + j
if s < best:
best = s
out = [x]
elif s == best:
out.append(x)
return out
if __name__ == "__main__":
print(Solution().findRestaurant(["Shogun","KFC"], ["KFC","Shogun"]))use std::collections::HashMap;
fn find_restaurant(list1: &[&str], list2: &[&str]) -> Vec<String> {
let pos: HashMap<&str, usize> = list1.iter().enumerate().map(|(i, &x)| (x, i)).collect();
let mut best = usize::MAX;
let mut out: Vec<String> = vec![];
for (j, &x) in list2.iter().enumerate() {
if let Some(&i) = pos.get(x) {
let s = i + j;
if s < best {
best = s;
out = vec![x.to_string()];
} else if s == best {
out.push(x.to_string());
}
}
}
out
}
fn main() {}