본문 바로가기

Codility

[Lesson 8][Leader] Dominator

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

# 최대 카운트 숫자의 인덱스 찾기
# 주의사항: A = [] 경우

import collections


def solution(A):
    N = len(A)
    if N == 0:
        return -1

    dic = collections.Counter(A)
    dominator = dic.most_common(1)[0]

    rst = []
    if N // 2 < dominator[1]:
        for i, x in enumerate(A):
            if dominator[0] == x:
                rst.append(i)

    if not rst:
        return -1
    return rst[-1]


print(solution([3, 4, 3, 2, 3, -1, 3, 3]))  # 0
print(solution([]))                         # -1