https://app.codility.com/programmers/lessons/8-leader/equi_leader/start/
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:
class Solution { public int solution(int[] 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.
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].
아이디어가 떠오르지 않아 타인의 풀이를 공부했다. 그런데 기대와 달리 그냥 직관적으로 구현한 듯하다 ㅎㅎ; 오른쪽 딕셔너리에서 삭제해주고 왼쪽 딕셔너리에 생성해준다. 그 후에 양쪽에 leader를 체크해서 둘다 성립하면 leader 개수 +1, 기존의 leader 숫자가 아니고 가장 최근에 보낸 숫자가 leader로 바뀌었을 수 있으므로 체킹하고 맞다면 leader 값을 변경해준다.
def solution(A):
lDic = {}
rDic = {}
lDic[A[0]] = 1
leader = 0
lmax = A[0]
for n in A[1:]:
if n in rDic:
rDic[n] += 1
else:
rDic[n] = 1
for i in range(1, len(A)):
if lDic[lmax] > i/2 and lmax in rDic and rDic[lmax] > (len(A)-i)/2:
leader += 1
elif lDic[A[i-1]] > i/2 and A[i-1] in rDic and rDic[A[i-1]] > (len(A)-i)/2:
leader += 1
lmax = A[i-1]
rDic[A[i]] -= 1
if A[i] in lDic:
lDic[A[i]] += 1
else:
lDic[A[i]] = 1
return leader