๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/์ธํ”„๋Ÿฐ(inflearn)

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] section05 - 6 - ํ•™๊ธ‰ํšŒ์žฅ

by YWTechIT 2021. 8. 29.
728x90

๐Ÿ“ section05 - 6 - ํ•™๊ธ‰ํšŒ์žฅ

ํˆฌํ‘œ์šฉ์ง€๋ฅผ ๋ณด๊ณ  ์–ด๋–ค ๊ธฐํ˜ธ์˜ ํ›„๋ณด๊ฐ€ ํ•™๊ธ‰ํšŒ์žฅ์ด ๋˜์—ˆ๋Š”์ง€ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. ์ด๋Ÿฐ ์œ ํ˜•์€ ํ•ด์‰ฌ(hash)๋กœ ํ’€๋ฉด๋œ๋‹ค. JS์—์„œ hash ๋ฌธ์ œ๋Š” key:value ํ˜•ํƒœ์ธ object๋กœ ํ’€๋ฉด ๋  ์ค„ ์•Œ์•˜๋Š”๋ฐ, ES6 ๋ฌธ๋ฒ•์— ์ƒˆ๋กœ์šด ์ž๋ฃŒ๊ตฌ์กฐ์ธ Map ํ˜•์œผ๋กœ ํ‘ธ๋Š”๊ฒƒ์ด ๋” ์‰ฌ์› ๋‹ค.

 

๊ธฐ๋ณธ์ ์œผ๋กœ object์˜ key๋Š” string | symbolํ˜•๋งŒ ๊ฐ€๋Šฅํ•˜์ง€๋งŒ Map์˜ key๋Š” ํ•จ์ˆ˜, ๊ฐ์ฒด, ๋ชจ๋“  ๊ธฐ๋ณธ ์š”์†Œ๋ฅผ ํฌํ•จํ•  ์ˆ˜ ์žˆ๋‹ค. ๋˜ํ•œ object๋Š” nonIterable์ด๋ผ์„œ for๋ฌธ ๋Œ€์‹  Object.entries() | Object.keys() | Object.values()๋ฅผ ์‚ฌ์šฉํ–ˆ์ง€๋งŒ Map์€ iterable ํ•˜๊ธฐ ๋•Œ๋ฌธ์— for๋ฌธ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ๋˜ํ•œ, object์˜ ์ˆœ์„œ๋Š” random์ด์ง€๋งŒ, Map์˜ ์ˆœ์„œ๋Š” sequenceํ•˜๋‹ค.

 

Map๊ณผ object์˜ ์ฐจ์ด๋ฅผ ๋” ๋ณด๊ณ  ์‹ถ๋‹ค๋ฉด MDN์„ ์ฐธ๊ณ ํ•˜์ž. ์•Œ๊ณ ๋ฆฌ์ฆ˜์—์„œ Map์ฒ˜๋Ÿผ key:valueํ˜•์„ iterableํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ํŠน์ง•๋งŒ์œผ๋กœ๋„ ์ถฉ๋ถ„ํžˆ ์‚ฌ์šฉ๊ฐ€์น˜๊ฐ€ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•œ๋‹ค.

 

  1. ํˆฌํ‘œ์šฉ์ง€๋ฅผ hash๊ฐ’์œผ๋กœ ๊ฐ๊ฐ ์ €์žฅํ•œ๋‹ค.
  2. ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ key, value๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ๊ฐ€์žฅ ๋งŽ์€ ํˆฌํ‘œ์ˆ˜๋ฅผ ๊ฐ€์ง„ ํ›„๋ณด๋ฅผ ์ตœ๋Œ€ ํ›„๋ณด๋กœ ๊ฐฑ์‹ ์‹œํ‚จ๋‹ค.

 

728x90

 

let n = 15;
let votes = "BACBACCACCBDEDE";

console.log(solution(n, votes));

function solution(n, votes){
  let vote = new Map();
  let maxVote = Number.MIN_SAFE_INTEGER;
  let maxCandidate;

  for (let x of votes){
    if (vote.has(x)) vote.set(x, vote.get(x)+1);
    else vote.set(x, 1);
  }

  vote.forEach((numberOfVote, candidate) => {
    if(numberOfVote>maxVote) maxVote=numberOfVote, maxCandidate=candidate;
  })
  return maxCandidate;
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€