Dominator

HeeSeong·2021년 6월 12일
0

Codility

목록 보기
22/34
post-thumbnail

🔗 문제 링크

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


❔ 문제 설명


An array A consisting of N integers is given. The dominator of array A is the value that occurs in more than half of the elements of A.

For example, consider array A such that

A[0] = 3 A[1] = 4 A[2] = 3
A[3] = 2 A[4] = 3 A[5] = -1
A[6] = 3 A[7] = 3

The dominator of A is 3 because it occurs in 5 out of 8 elements of A (namely in those with indices 0, 2, 4, 6 and 7) and 5 is more than a half of 8.

Write a function

def solution(A)

that, given an array A consisting of N integers, returns index of any element of array A in which the dominator of A occurs. The function should return −1 if array A does not have a dominator.

For example, given array A such that

A[0] = 3 A[1] = 4 A[2] = 3
A[3] = 2 A[4] = 3 A[5] = -1
A[6] = 3 A[7] = 3

the function may return 0, 2, 4, 6 or 7, as explained above.


⚠️ 제한사항


  • N is an integer within the range [0..100,000];

  • each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].



💡 풀이 (언어 : Python)


우연히 pythonic한 코드를 설명하는 파이썬 유튜브를 보다가 counter라는 모듈의 신기한 기능을 본적이 있다. 그리고 이 문제를 봤을 때 바로 이걸 쓰면 쉽게 구하겠구나! 느낌이 왔다. counter는 리스트의 각 원소들의 빈도수를 케이스별로 모두 구해준다. 가장 빈도수 높은 순으로 정렬되며, most_common(n)을 사용하면 빈도수 n순위의 [(값, 빈도)] 형태를 얻을 수 있다. 아무것도 안들어간 리스트는 작성한 알고리즘에서는 커버가 안돼서 별도로 if 처리했다. 시간복잡도는 O(Nlog(N))O(N*log(N)) 또는 O(N)O(N)

from collections import Counter 

def solution(A):
    counter = Counter(A)
    
    if len(A) == 0:
        return -1
        
    dominator = counter.most_common(1)[0][0]

    if A.count(dominator) > len(A) / 2:
        return A.index(dominator)
    else:
        return -1
profile
끊임없이 성장하고 싶은 개발자

0개의 댓글