"파이썬" 이여서 쉬운 문제
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 |