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] = 2we 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] = 2the function should return 2, as explained above.
Assume that:
- 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].
Complexity:
- expected worst-case time complexity is O(N);
- expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Solution:
解题思路:首先检查数组中是否存在leader。如果数组中不存在leader,必然不存在 equil leader。
证明:假设数组元素个数为n, 在下标S处将数组分割为两个子数组,如果S是equil leader, 那么数组中必然存在一个出现次数大于(S+1)/2 + (N-S-1)/2 >= (N)/2的数。
找到leader后,利用前缀计数组prefixCnt[0...N-1]保存子数组[0...i] (0 <= i <= N-1)中leader出现的次数。
那么对于index S(0 <= S <= N-1),子数组 A[0...S]中leader个数为pfefixCnt[S],子数组A[S+1...N-1] 中leader个数为数组A中leader出现总数减去prefixCnt[S],只要保证这两个子数组中leader的出现次数都大于相应子数组长度的一半即可。
def
solution(A):
candidate_ele
=
''
candidate_cnt
=
0
for
value
in
A:
if
candidate_ele
=
=
'':
candidate_ele
=
value
candidate_cnt
=
1
else
:
if
value !
=
candidate_ele:
candidate_cnt
-
=
1
if
candidate_cnt
=
=
0
:
candidate_ele
=
''
else
:
candidate_cnt
+
=
1
if
candidate_cnt
=
=
0
:
return
0
cnt
=
0
last_idx
=
0
for
idx, value
in
enumerate
(A):
if
value
=
=
candidate_ele:
cnt
+
=
1
last_idx
=
idx
if
cnt <
len
(A)
/
/
2
:
return
0
equi_cnt
=
0
cnt_to_the_left
=
0
for
idx, value
in
enumerate
(A):
if
value
=
=
candidate_ele:
cnt_to_the_left
+
=
1
if
cnt_to_the_left > (idx
+
1
)
/
/
2
and
\
cnt
-
cnt_to_the_left > (
len
(A)
-
idx
-
1
)
/
/
2
:
equi_cnt
+
=
1
return
equi_cnt