본문 바로가기
Problem Solving/Codility

[Python] 8.1. Dominator

by 부르르 2021. 4. 5.

https://app.codility.com/demo/results/trainingKJKX8S-C3B/

 

Test results - Codility

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 dom

app.codility.com


Task Score

100%

Correctness

100%

Performance

100%

Detected time complexity

O(N * log(N)) or O(N)

def solution(A): ​​​​n = len(A) ​​​​stack = [] ​​​​ ​​​​for a in A: ​​​​​​​​if not stack: ​​​​​​​​​​​​stack.append(a) ​​​​​​​​else: ​​​​​​​​​​​​if stack[-1] != a: ​​​​​​​​​​​​​​​​stack.pop() ​​​​​​​​​​​​else: ​​​​​​​​​​​​​​​​stack.append(a) ​​​​​​​​​​​​​​​​ ​​​​cnt = 0 ​​​​for a in A: ​​​​​​​​if stack and a == stack[-1]: ​​​​​​​​​​​​cnt += 1 ​​​​ ​​​​if cnt >= n//2+1: ​​​​​​​​return A.index(stack[-1]) ​​​​else: ​​​​​​​​return -1

 

문제를 푸는데 도움이 된 테스트 케이스

[]
[0]
[1,1]
[1,2]
[1,2,3]
[2,1,1]
[1,1,2,2]
[2,1,1,1]
[1,1,2,2,2]

 

728x90
반응형

'Problem Solving > Codility' 카테고리의 다른 글

[Python] FirstUnique  (0) 2021.07.15
[Python] DisappearingPairs  (0) 2021.07.15
[Python] 7.3. Nesting  (0) 2021.03.30
[Python] 7.2. Fish  (0) 2021.03.29
[Python] 7.1. Brackets  (0) 2021.03.27

댓글