ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

https://app.codility.com/programmers/lessons/8-leader/dominator/

 

Dominator coding task - Learn to Code - Codility

Find an index of an array such that its value occurs at more than half of indices in the array.

app.codility.com

 


๋ฌธ์ œ ํ’€์ด

๋ฆฌ์ŠคํŠธ์˜ ๊ฐ’ ๋“ค ์ค‘, ํ•˜๋‚˜์˜ ์ˆ˜๊ฐ€ ๋ฆฌ์ŠคํŠธ ๊ธธ์ด์˜ ์ ˆ๋ฐ˜ ์ด์ƒ์„ ์ฐจ์ง€ํ•˜๋ฉด dominator๊ฐ€ ๋˜๊ณ , ํ•ด๋‹นํ•˜๋Š” ์ˆ˜์˜ ๋ฐฐ์—ด๋‚ด ์ธ๋ฑ์Šค ์ค‘ ์•„๋ฌด ๊ฐ’์ด๋‚˜ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋˜๋Š” ๋ฌธ์ œ์ด๋‹ค.


์ฝ”๋“œ

def solution(A):
    cnt = {}
    length = len(A)
    if not length:
        return -1

    for i, num in enumerate(A):
        if num not in cnt:
            cnt[num] = [i]
        else:
            cnt[num].append(i)
    sort = sorted(cnt.values(), key=len)[-1]
    return sort[0] if len(sort) > length // 2 else -1
  • ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ํ†ตํ•ด ๋ฆฌ์ŠคํŠธ ๋‚ด์˜ ๊ฐ๊ฐ์˜ ๊ฐ’์— ๋Œ€ํ•œ ์ธ๋ฑ์Šค๋ฅผ ๋ชจ๋‘ ๋‹ด๊ณ , ๊ธฐ์กด ๋ฆฌ์ŠคํŠธ ๊ธธ์ด์˜ ์ ˆ๋ฐ˜์„ ๋„˜๋Š”์ง€ ํ™•์ธํ•œ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€