반응형
1. 문제
- 문자열 list1, list2가 주어질 때, 공통으로 존재하는 문자열의 두 인덱스 차이가 가장 작은 문자열을 담아 반환하라.
2. 해결
function findRestaurant(list1: string[], list2: string[]): string[] {
const map1 = new Map<string, number>();
const map2 = new Map<string, number>();
for(let i = 0; i < list1.length; i++) {
map1.set(list1[i], i)
}
for(let i = 0; i < list2.length; i++) {
map2.set(list2[i], i)
}
const result = [];
let min = Number.MAX_SAFE_INTEGER;
for(const [str, idx] of map1) {
if(map2.has(str)) {
const target = map2.get(str);
if(target + idx <= min) {
if(target + idx < min)
result.length = 0;
min = target + idx;
result.push(str);
}
}
}
return result
};
- 두 문자 배열을 탐색하며 Map에 문자열-인덱스로 맵핑.
- 한쪽 Map을 탐색하며, 다른 쪽 Map에 있으면서 최소값 갱신.
- 최소값보다 작은 경우가 나오면 result 배열을 초기화 후 담기.