📄문제

✏️풀이
재영
진짜 해시 문제였군요!
이 역시 최대한
for
문을 줄이려고 했지만, 결국 O(N^2 * log N)
이 최대인 것 같았읍니다...!일단 정말 문제에서 요구한 대로 똑같이 풀었던 거 같네요.
- 도메인과 cp를 먼저 분리하자.
- 분리시킨 뒤에, 도메인도
.
기준으로 다 분리하자.
- 그런데 지금 뒷쪽에서부터 계산한다.
- 따라서 기존 배열도 거꾸로 하면서,
acc + cur
부분을 거꾸로 해준다.
- 이제 해시를 계속해서 업데이트해준다.
- 결과를 반환할 때는
map
친구들을 다 꺼내와서,map
으로 결과와 똑같은 형식으로 만들어주어 반환한다.
const subdomainVisits = function (cpdomains) { const map = new Map(); cpdomains.forEach((cpdomain) => { const [cp, domain] = cpdomain.split(" "); domain .split(".") .reverse() .reduce((acc, cur) => { const now = acc ? cur + "." + acc : cur; map.set(now, parseInt(map.get(now) ?? 0) + parseInt(cp)); return now; }, "")}); return [...map.entries()].map(([key, value]) => `${value} ${key}`); };
시간 복잡도도 괜찮게 나오네요. 굿!
은찬
const subdomainVisits =(cpdomains) => { const answer = []; const map = new Map(); for(let i = 0; i < cpdomains.length; i++){ const splitedString = cpdomains[i].split(" "); const rep = parseInt(splitedString[0]); const domains = splitedString[1].split("."); for(let j = 0; j < domains.length; j++){ const key = domains.slice(-j).join("."); const value = map.get(key) ?? []; map.set(key, [...value, rep]); } } for(const [key, value] of map){ let sum = 0; for(let i = 0; i < value.length; i++){ sum += value[i]; } answer.push(`${sum} ${key}`); } return answer; };
현석
var subdomainVisits = function(cpdomains) { const map = new Map() cpdomains.forEach(el => { const [rep, domain] = el.split(' ') domain .split('.') .reduce((acc, item) => { acc = acc.map(el => [...el, item]) acc.push([item]) return acc; }, []) .map(el => el.join('.')) .forEach(el => { if (map.has(el)) { map.set(el, map.get(el) + Number(rep)) return; } map.set(el, Number(rep)); }) }) return Array .from(map) .map(el => `${el[1]} ${el[0]}`) };
효성
오오 96.01% 나왔어요.
var subdomainVisits = function(cpdomains) { const hash = new Map(); cpdomains.forEach(domain => { const [cp, name] = domain.split(' '); const visitCnt = parseInt(cp); addVisitCnt(name, visitCnt, hash) for(let i=0; i<name.length; i++) { if(name[i] === '.') { const str = name.slice(i+1); addVisitCnt(str, visitCnt, hash) } } }); let res = []; hash.forEach((key, value) => { res.push(`${key}`+ " " + `${value}`); }); return res; }; function addVisitCnt(str, visitCnt, hash) { if(hash.has(str)) { hash.set(str, hash.get(str) + visitCnt); } else { hash.set(str, visitCnt); } }