let's get IT with DAVINA ๐Ÿ’ป

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค]Lv0. ์ตœ๋นˆ๊ฐ’ ๊ตฌํ•˜๊ธฐ ๋ณธ๋ฌธ

DEV_IN/๋ฌธ์ œํ’€์ด

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค]Lv0. ์ตœ๋นˆ๊ฐ’ ๊ตฌํ•˜๊ธฐ

๋‹ค๋นˆ์น˜์ฝ”๋“œ๐Ÿ’Ž 2023. 3. 7. 13:52
์ตœ๋นˆ๊ฐ’ ๊ตฌํ•˜๊ธฐ ๋„ˆ๋ฌด ์–ด๋ ค์› ๋‹ค.. ๋‹ค๋นˆ๊ฐ’ ๊ตฌํ•˜๊ธฐ..
ํ˜ผ์ž ํž˜์œผ๋กœ๋Š” ๋„์ €ํžˆ ์ƒ๊ฐ์•ˆ๋‚˜์„œ ์—ฌ๋Ÿฌ ๋ธ”๋กœ๊ทธ๋ฅผ ์ฐธ๊ณ ํ•ด๋ดค์ง€๋งŒ.. ์ฒ˜์Œ์— ๋ฐฐ์—ด์ด ์•„๋‹Œ ๋นˆ ๊ฐ์ฒด์— ๋„ฃ์–ด์ค€๋‹ค๋Š” ์ƒ๊ฐ์„ ํ•˜๋Š”๊ฒŒ ์ ค ๋ฉ˜๋ถ•์ด์—ˆ๋‹ค..
๊ฒจ์šฐ๊ฒจ์šฐ ์—ฌ๋Ÿฌ ๊ฐœ๋ฅผ ์งฌ๋ฝ•ํ•ด์„œ ๋‚ด๊ฐ€ ์ดํ•ดํ•œ๋Œ€๋กœ ์ฝ”๋“œ๋ฅผ ์งœ๊ณ  ๊ฒจ์šฐ ํ†ต๊ณผ ํ–ˆ๋‹ค์š”..

โ“ ๋ฌธ์ œ ์„ค๋ช…

์ตœ๋นˆ๊ฐ’์€ ์ฃผ์–ด์ง„ ๊ฐ’ ์ค‘์—์„œ ๊ฐ€์žฅ ์ž์ฃผ ๋‚˜์˜ค๋Š” ๊ฐ’์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค. ์ •์ˆ˜ ๋ฐฐ์—ด array๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, ์ตœ๋นˆ๊ฐ’์„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด๋ณด์„ธ์š”. ์ตœ๋นˆ๊ฐ’์ด ์—ฌ๋Ÿฌ ๊ฐœ๋ฉด -1์„ return ํ•ฉ๋‹ˆ๋‹ค.

๐Ÿšซ ์ œํ•œ์‚ฌํ•ญ

  • 0 < array์˜ ๊ธธ์ด < 100
  • 0 ≤ array์˜ ์›์†Œ < 1000

๐Ÿ—๏ธ ์ž…์ถœ๋ ฅ ์˜ˆ

array result
[1, 2, 3, 3, 3, 4] 3
[1, 1, 2, 2] -1
[1] 1

๐Ÿ’ก ๋น„๋‹ˆ's ํ’€์ด

function solution(array) {      
    let count={}; //{1:1,2:1,3:3,4:1} {1:2,2:2}
    for(let i=0;i<array.length;i++){
        if(count[array[i]]===undefined){ //์ฒ˜์Œ๋ณด๋Š” ์š”์†Œ์•ผ?
            count[array[i]]=1; //count 1๋ถ€ํ„ฐ ์‹œ์ž‘ 
        } else { //์ค‘๋ณต๋œ ์š”์†Œ๋ฉด
            count[array[i]]++; //count ์ฆ๊ฐ€
        }
    }
    
    let newArr=[];
    for(let key in count){
        newArr.push(count[key]) //[1,1,3,1] [2,2]
    }
    let maxCount= Math.max(...newArr); //๊ฐ€์žฅ ๋งŽ์ด ๋‚˜์˜จ ํšŸ์ˆ˜๋ฅผ ์•Œ๋ ค์ฃผ์ง€
    
    let newArr2=[];
        for(let key in count){
            if(count[key]===maxCount)
        newArr2.push(key) //ํšŸ์ˆ˜ ๊ฐ€์žฅ ๋งŽ์ด ๋‚˜์˜จ๊ฒŒ ๋ฌด์Šจ ๊ฐ’์ธ์ง€ ๋„ฃ์–ด์คญ (stringํƒ€์ž…์œผ๋กœ ๋“ค์–ด๊ฐ€๊ฒ ์ง€?)
    }
    if(newArr2.length>1){ //๋‘ ๊ฐœ ์ด์ƒ์ด๋ฉด -1
        return -1
    } else {
        return Number(newArr2[0]) //ํ•œ ๊ฐœ๋ฉด ๊ทธ ๊ฐ’์ด ๋ญ์–Œ?! (numberํƒ€์ž…์œผ๋กœ ๋ฐ”๊ฟ”์ค˜)
    }
}
Comments