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

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

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

 

EquiLeader coding task - Learn to Code - Codility

Find the index S such that the leaders of the sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N - 1] are the same.

app.codility.com


๋ฌธ์ œ ํ’€์ด

Dominator ๋ฌธ์ œ์™€๋Š” ๋‹ค๋ฅด๊ฒŒ, ๊ฐ ๊ตฌ๊ฐ„ ๋ณ„๋กœ left, right์˜ leader๊ฐ€ ์ผ์น˜ํ•˜๋Š”์ง€ ํ™•์ธํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

์ฃผ์–ด์ง„ ์˜ˆ์‹œ์˜ ๊ฒฝ์šฐ 4, 3, 4, 4, 4, 2์ด๋‹ค. ๋ฆฌ์ŠคํŠธ์˜ ์•ž์—์„œ ๋ถ€ํ„ฐ ๊ตฌ๊ฐ„์„ left, right๋กœ ๋‚˜๋ˆ„๊ฒŒ ๋˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

 

left

right

Phase 1

4

3

4

4

4

2

 

left

right

Phase 2

4

3

4

4

4

2

 

left

right

Phase 3

4

3

4

4

4

2

 

left

right

Phase 4

4

3

4

4

4

2

 

left

right

Phase 5

4

3

4

4

4

2

 

  • 1 ๋‹จ๊ณ„์—์„œ๋Š” left leader๋Š” 4์ด๊ณ , right leader๋Š” 4์ด๊ธฐ ๋•Œ๋ฌธ์— ๊ฒฝ์šฐ์˜ ์ˆ˜์— ํฌํ•จํ•œ๋‹ค.

  • 2 ๋‹จ๊ณ„๋Š” left leader๋Š” ์—†๊ณ , right leader๋Š” 4์ด๊ธฐ ๋•Œ๋ฌธ์— ๊ฒฝ์šฐ์˜ ์ˆ˜์— ํฌํ•จํ•˜์ง€ ์•Š๋Š”๋‹ค.

  • 3 ๋‹จ๊ณ„๋Š” left leader๋Š” 4์ด๊ณ , right leader๋Š” 4์ด๊ธฐ ๋•Œ๋ฌธ์— ๊ฒฝ์šฐ์˜ ์ˆ˜์— ํฌํ•จํ•œ๋‹ค.

  • 4, 5 ๋‹จ๊ณ„๋Š” left leader์™€ right leader๊ฐ€ ๋‹ค๋ฅด๊ธฐ ๋•Œ๋ฌธ์— ๊ฒฝ์šฐ์˜ ์ˆ˜์— ํฌํ•จํ•˜์ง€ ์•Š๋Š”๋‹ค.


์ฝ”๋“œ

def solution(A):
    left, right = {}, {}
    left_length, right_length = 0, len(A)
    left_leader = 0
    cnt, left_cnt = 0, 0

    for num in A:
        try:
            right[num] += 1
        except KeyError:
            right[num] = 1

    for i in range(len(A)):
        right[A[i]] -= 1
        right_length -= 1

        try:
            left[A[i]] += 1
        except KeyError:
            left[A[i]] = 1

        left_length += 1

        if left[A[i]] > left_cnt:
            left_leader = A[i]
            left_cnt = left[A[i]]

        if right[left_leader] > right_length // 2 and left_cnt > left_length // 2:
            cnt += 1

    return cnt
  • right์— ๊ฐ๊ฐ์˜ ๊ฐ’๋“ค์„ ์นด์šดํŠธํ•œ๋‹ค.

  • right์— ์นด์šดํŠธ๋œ ๊ฐ’์„ left๋กœ ์˜ฎ๊ฒจ์ฃผ์–ด ๊ฐ๊ฐ์˜ leader๋ฅผ ๋น„๊ตํ•˜์—ฌ ๋‹ต์„ ์ฐพ์„ ์ˆ˜ ์žˆ๋‹ค.

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