Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Programmers

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

๊ฐ์ž ๐Ÿฅ” 2021. 8. 18. 16:05
๋ฐ˜์‘ํ˜•

 

๋ฌธ์ œ๋งํฌ

https://programmers.co.kr/learn/courses/30/lessons/1845

 

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

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

programmers.co.kr

 

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

  1. ํฐ์ผ“๋ชฌ์˜ ์ค‘๋ณต๋˜๋Š” ๊ฐ’์„ ์—†์• ์ค€ ํ›„ ๊ฐฏ์ˆ˜๋ฅผ ์„ธ์–ด์ค€๋‹ค.
  2. ์ตœ์ข… n๊ฐœ์—์„œ n/2๊ฐœ์˜ ํฐ์ผ“๋ชฌ์„ ๊ฐ€์ ธ๊ฐˆ ์ˆ˜ ์žˆ์œผ๋‹ˆ, n/2 ๊ฐ’์„ ๊ตฌํ•ด์ค€๋‹ค.
  3. ์œ„์˜ ๋‘ ๊ฐ’์„ ๋น„๊ตํ•˜์—ฌ ๋ช‡ ์ข…๋ฅ˜๋ฅผ ๊ฐ€์ ธ๊ฐˆ ์ˆ˜ ์žˆ๋Š”์ง€ ์‚ดํŽด๋ณธ๋‹ค.
def solution(nums):
    have = len(nums)/2
    total = set(nums)
    total_len = len(total)
    if have > total_len:
        answer = total_len
    else:
        answer = have
    return answer

 

 

๋‹ค๋ฅธ์‚ฌ๋žŒํ’€์ด

๊ทธ๋ƒฅ min ์—ฐ์‚ฐ์„ ์ด์šฉํ•ด์„œ ํ‘ผ ๋ฐฉ๋ฒ•์ด ์—ญ๋Œ€๊ธ‰์œผ๋กœ ๊ฐ„๋‹จํ–ˆ๋‹ค.

def solution(ls):
    return min(len(ls)/2, len(set(ls)))

์‚ฌ์‹ค ๋œฏ์–ด๋ณด๋ฉด ๋‚ด๊ฐ€ ๊ตฌํ•œ ๋ฐฉํ–ฅ๊ณผ ๊ฐ™์€ ๋ฐฉํ–ฅ์ด๋‹ค. ํ•ด๋‹น๋ฐฉ๋ฒ•์€ ๋ณ€์ˆ˜์„ค์ •๋„ ํ•˜์ง€์•Š์•„์„œ ๋ฉ”๋ชจ๋ฆฌ ํšจ์œจ์ด ๋” ์ข‹์„ ๊ฒƒ์ด๊ณ  ์ฝ”๋“œ๊ฐ€ ๊ธธ์ง€ ์•Š์•„ ์‹œ๊ฐ„๋ณต์žก๋„๋„ ์ข‹์„ ๊ฒƒ์ด๋‹ค. ๋‚˜๋„ if๋ฌธ์„ ์‚ฌ์šฉํ•ด์„œ ์ž‘์€๊ฐ’์„ ๊ณจ๋ผ๋‚ด๋Š” ๋ฐฉ๋ฒ•์ด ์•„๋‹Œ min์„ ์‚ฌ์šฉํ•ด์„œ ๋ณ€์ˆ˜ ํ• ๋‹น๋Ÿ‰๋„ ์ค„์ด๊ณ , if๋ฌธ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๋ฐฉ๋ฒ•์„ ์ž์ฃผ ์ด์šฉํ•ด๋ณด์•„์•ผ ๊ฒ ๋‹ค.

๋ฐ˜์‘ํ˜•