python 의 collections 에 most_common 과 부분합을 연관지어 풀면 쉽게 풀리는 문제이다.
Task description
A non-empty array A consisting of N integers is given.
The leader of this array is the value that occurs in more than half of the elements of A.
An equi leader is an index S such that 0 ≤ S < N − 1 and two sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have leaders of the same value.
For example, given array A such that:
A[0] = 4 A[1] = 3 A[2] = 4 A[3] = 4 A[4] = 4 A[5] = 2
we can find two equi leaders:
- 0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader, whose value is 4.
- 2, because sequences: (4, 3, 4) and (4, 4, 2) have the same leader, whose value is 4.
The goal is to count the number of equi leaders.
Write a function:
def solution(A)
that, given a non-empty array A consisting of N integers, returns the number of equi leaders.
For example, given:
A[0] = 4 A[1] = 3 A[2] = 4 A[3] = 4 A[4] = 4 A[5] = 2
the function should return 2, as explained above.
Write an efficient algorithm for the following assumptions:
- N is an integer within the range [1..100,000];
- each element of array A is an integer within the range [−1,000,000,000..1,000,000,000]
import collections
def solution(A):
answer=0
# write your code in Python 3.6
ans=collections.Counter(A).most_common(1)[0]
if ans[1]<=len(A)//2:
return 0
comons=[0]*len(A)
for i in range(len(A)):
if i==0 and A[i] == ans[0]:
comons[0]=1
elif A[i] == ans[0]:
comons[i]=comons[i-1]+1
else:
comons[i]=comons[i-1]
for i in range(len(A)-1):
before=comons[i]
after=comons[len(A)-1]-before
afterLen= len(A)-i-1
beforeLen=i+1
if before<= beforeLen//2 or after<=afterLen//2:
continue
else:
answer+=1
return answer
'알고리즘' 카테고리의 다른 글
코딜리티 MinPerimeterRectangle (0) | 2021.03.16 |
---|---|
코딜리티 CounterFactors (0) | 2021.03.16 |
Dominator 코딜리티 (0) | 2021.03.14 |
maxCounter 코딜리티 O(N+M) 그 마의 구간 (0) | 2021.03.14 |
프로그래머스 SQL 답지 (0) | 2021.03.12 |