๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

ํ”„์—” ๊ณต๋ถ€/๐Ÿซง ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณต๋ถ€

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/Javascript] ์ตœ๋นˆ๊ฐ’ ๊ตฌํ•˜๊ธฐ || ์ฝ”๋”ฉํ…Œ์ŠคํŠธ

728x90

<๋‚˜์˜ ํ’€์ด>

function solution(array) {
    const set = new Set(array);
    const map = new Map([...set].map(v => [v, 0]));
    array.map(v => map.has(v) && map.set(v, map.get(v) + 1))
    const countArr = [...map.values()];
    let resultArr = [];
    let maxNum = Math.max(...map.values());
    for (let i = 0; i < countArr.length; i++) {
        maxNum === countArr[i] && resultArr.push(countArr[i])
    }
    const index = countArr.findIndex(v => v === maxNum);
    return resultArr.length > 1 ? -1 : [...map.keys()][index];
}

set ์„ ์ด์šฉํ•ด์„œ ์ค‘๋ณต๋˜์ง€ ์•Š๋Š” ์ˆ˜๋ฅผ ๊ตฌํ•œ ํ›„, 

set ํ•œ ์ˆซ์ž๋“ค์„ key๋กœ, ์ดˆ๊ธฐ๊ฐ’ 0์„ value๋กœ map์œผ๋กœ ๋งŒ๋“ค์–ด์คฌ๋‹ค.

map ์ด ์žˆ๋‹ค๋ฉด value๋ฅผ +1 ํ•ด์„œ ๋‹ค์‹œ set ํ•ด์คฌ๋‹ค.

๊ทธ๋ž˜์„œ count ํ•œ value ๋“ค์„ ๊ฐ€์ง€๋Š” map์ด ์™„์„ฑ๋๋‹ค.

์—ฌ๊ธฐ์„œ ์ตœ๋Œ€๊ฐ’์„ ๊ตฌํ•œ ํ›„ ์ตœ๋นˆ๊ฐ’์„ ๋ชจ์•„์„œ length ๋ฅผ ๋น„๊ตํ–ˆ๋Š”๋ฐ, 

๋‹ค ํ†ต๊ณผํ•˜๊ณ  ๋‹ค๋ฅธ ํ’€์ด๋ฅผ ๋ณด๋‹ˆ

=> ๊ทธ๋ƒฅ sort ๋ฅผ ํ†ตํ•ด ์ค„์ง€์€ ๋‹ค์Œ, [0] ๊ณผ [1] ์„ ๋น„๊ตํ•ด ๊ฐ™์œผ๋ฉด -> ์ตœ๋นˆ๊ฐ’ 2๊ฐœ ์ด์ƒ, ๋‹ค๋ฅด๋ฉด ์ตœ๋นˆ๊ฐ’ 1๊ฐœ ๋กœ ๊ฒฐ๋ก ์€ ๋‚ด๋ ธ์–ด๋„ ๋  ๋ป” ํ–ˆ๋‹ค.

(์ด ๋ถ€๋ถ„์ด ์ฝ”๋“œ๊ฐ€ ๋Š˜์–ด๋‚จ)

map ์€ ์ˆœ์„œ๋ฅผ ๊ธฐ์–ตํ•˜๊ธฐ์— ์ตœ๋นˆ๊ฐ’์ด ํ•˜๋‚˜๋ผ๋ฉด, ๊ฐ™์€ index ๋ฅผ ๊ฐ€์ง„ key ๋ฅผ ์ฐพ์•„์„œ ๋ฐ˜ํ™˜ํ•ด์คฌ๋‹ค.

 

 

<๋” ๊ดœ์ฐฎ๋‹ค๊ณ  ์ƒ๊ฐ๋˜๋Š” ํ’€์ด>

function solution(array) {
    let m = new Map();
    for (let n of array) m.set(n, (m.get(n) || 0)+1);
    m = [...m].sort((a,b)=>b[1]-a[1]);
    return m.length === 1 || m[0][1] > m[1][1] ? m[0][0] : -1;
}

 

 

 

 

๊ทธ๋‚˜์ €๋‚˜ ์ด ๋ฌธ์ œ ํ•œ๋‹ฌ ์ „ ์ฏค์— ๋„์ „ํ–ˆ์„ ๋• ๋„ˆ๋ฌด ๋ณต์žกํ•˜๊ณ  ์–ด๋ ต๊ฒŒ ๋Š๊ปด์ ธ์„œ 

ํ•œ- ๋‘์‹œ๊ฐ„ ์ด๋‚ด๋กœ ๊ณ ๋ฏผํ•˜๋‹ค๊ฐ€ ํฌ๊ธฐํ–ˆ์—ˆ๋Š”๋ฐ, 

์ง€๊ธˆ ๋ณด๋‹ˆ map ์˜ value ์™€ key ๋ฅผ ์–ด๋–ป๊ฒŒ ๊ฐ€์ ธ์˜ค๋Š”์ง€๋งŒ ์•Œ๋ฉด ๋‚˜์˜์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™๋‹ค.

728x90
๋ฐ˜์‘ํ˜•