문제
문제 링크 : Count Common Words With One Occurrence
풀이
var countWords = function(words1, words2) {
let cnt = 0
for(let i=0; i<words1.length; i++) {
if( words1.indexOf(words1[i]) === words1.lastIndexOf(words1[i])
&& words2.indexOf(words1[i]) > -1 && words2.indexOf(words1[i]) === words2.lastIndexOf(words1[i])
) cnt ++
}
return cnt
};
- 배열 words1에 존재하면서 하나만 존재(indexOf === lastIndexOf), 배열 words2에 존재(indexOf > -1)하면서 하나만 존재(indexOf ==== lastIndexOf)를 찾아 cnt++
- Runtime 80 ms, Memory 44.22 MB
다른 풀이
var countWords = function(words1, words2) {
let map1=new Map()
let map2=new Map()
for(let i=0;i<words1.length;i++)
{
map1.set(words1[i],map1.get(words1[i])+1||1)
}
for(let i=0;i<words2.length;i++)
{
map2.set(words2[i],map2.get(words2[i])+1||1)
}
let count=0;
for(const key of map1)
{
if(key[1]===1)
{
if(map2.get(key[0])===1) count++
}
}
return count
};
- Map을 사용하여 카운팅
- Runtime 66 ms, Memory 45.92 MB