A non-empty zero-indexed 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:
int solution(vector<int> &A);
that, given a non-empty zero-indexed 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.
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).
Elements of input arrays can be modified.
解题思路:首先检查数组中是否存在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的出现次数都大于相应子数组长度的一半即可。
参考代码如下:
// you can use includes, for example:
// #include <algorithm>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(vector<int> &A) {
// write your code in C++11
if(A.size() < 2) return 0;
int leader = A[0];
int count = 1;
int size = A.size();
for(int i = 1; i < size; i++){
if(A[i] == leader){
count++;
}
else{
count --;
if(!count){
leader = A[i];
count = 1;
}
}
}
//valid whether the leader exists or not
count = 0;
vector<int> prefixCnt(size, 0);
for(int i = 0; i < size; i++){
if(A[i] == leader) count++;
prefixCnt[i] = count;
}
if(count <= (size >> 1)) return 0;
int equi_leaders = 0;
for(int i = 0; i < size-1; i++){
if(prefixCnt[i] > ((i+1) >> 1) && count - prefixCnt[i] > ((size-i-1) >> 1) )
equi_leaders ++;
}
return equi_leaders;
}