๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“– Problem Solution/Programmers

[JS] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ํฐ์ผ“๋ชฌ

by Fomagran ๐Ÿ’ป 2022. 2. 6.
728x90
๋ฐ˜์‘ํ˜•

Problem

 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ํฐ์ผ“๋ชฌ

๋‹น์‹ ์€ ํฐ์ผ“๋ชฌ์„ ์žก๊ธฐ ์œ„ํ•œ ์˜ค๋žœ ์—ฌํ–‰ ๋์—, ํ™ ๋ฐ•์‚ฌ๋‹˜์˜ ์—ฐ๊ตฌ์‹ค์— ๋„์ฐฉํ–ˆ์Šต๋‹ˆ๋‹ค. ํ™ ๋ฐ•์‚ฌ๋‹˜์€ ๋‹น์‹ ์—๊ฒŒ ์ž์‹ ์˜ ์—ฐ๊ตฌ์‹ค์— ์žˆ๋Š” ์ด N ๋งˆ๋ฆฌ์˜ ํฐ์ผ“๋ชฌ ์ค‘์—์„œ N/2๋งˆ๋ฆฌ๋ฅผ ๊ฐ€์ ธ๊ฐ€๋„ ์ข‹๋‹ค๊ณ  ํ–ˆ์Šต๋‹ˆ๋‹ค.

programmers.co.kr


Solution

 

1. nums์˜ ๊ธธ์ด์˜ ๋ฐ˜์„ ๊ตฌํ•œ๋‹ค.

 

let half = nums.length/2

 

2. Set์— nums์— ์žˆ๋Š” ๋ฒˆํ˜ธ๋ฅผ ๋„ฃ๋Š”๋‹ค.

 

    let set = new Set()
    for (let i = 0; i < nums.length; i++) {
        set.add(nums[i])
    }

 

3. Set์˜ ์‚ฌ์ด์ฆˆ์™€ nums์˜ ๊ธธ์ด์˜ ๋ฐ˜๊ณผ ๋น„๊ตํ•ด ๋” ์ž‘์€ ๊ฒƒ์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

 

return Math.min(set.size,half)

Source Code

 

function solution(nums) {
    let half = nums.length/2
    let set = new Set()
    for (let i = 0; i < nums.length; i++) {
        set.add(nums[i])
    }
    return Math.min(set.size,half)
}
728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€