기타/Codility

[Easy] Dominator

백곰곰 2022. 5. 26. 22:49
728x90
반응형

[문제]

전체 배열의 중에서 절반 이상 반복되어 나타나는 숫자가 있는지 찾고 있다면 그 숫자의 index를 리턴하는 문제

 

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

[코드]

Dictionary를 이용해 값 별로 등장 횟수를 카운팅 함

시간복잡도 : O(N*log(N)) or O(N)

python
def solution(A): # write your code in Python 3.6 max = 0 max_val = 0 dict= {} for i in A : if dict.get(i, -1) == -1 : dict[i]=1 else : dict[i] += 1 if dict[i] > max : max_val = i max = dict[i] if max > int(len(A)/2) : return A.index(max_val) else : return -1
728x90

'기타 > Codility' 카테고리의 다른 글

[Easy] CountFactors  (0) 2022.05.30
[Easy] MaxProfit  (0) 2022.05.30
[Easy] Fish  (0) 2022.05.26
[Easy] Brackets  (0) 2022.05.25
[Easy] Distinct  (0) 2022.05.25