티스토리 뷰

알고리즘

Dominator 코딜리티

killog 2021. 3. 14. 11:49
반응형

"파이썬" 이여서 쉬운 문제

Task description

 

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.

Write an efficient algorithm for the following assumptions:

  • 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].

Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

 

import collections
def solution(A):
    if len(A)==0:
        return -1
    # write your code in Python 3.6
    answer=collections.Counter(A).most_common(1)[0]
    if answer[1]>(len(A)//2):
        return A.index(answer[0])
    else:
        return -1
반응형

'알고리즘' 카테고리의 다른 글

코딜리티 CounterFactors  (0) 2021.03.16
코딜리티 EquiLeader  (0) 2021.03.14
maxCounter 코딜리티 O(N+M) 그 마의 구간  (0) 2021.03.14
프로그래머스 SQL 답지  (0) 2021.03.12
틀림 프로그래머스 3*n 타일링 dp 문제  (0) 2021.03.11
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함