题目
已知⼀个整数序列A = ,其中(),()。若存在 ,且 ,,则称x 为 A 的主元素。 例如,,则5是主元素; 若 ,则 A 中没有主元素,假设A中的 n 个元素保存在一个一维数组中,请设计一个尽可能高效的算法,找出数组元素中的主元素,若存在主元素则输出该元素,否则输出-1.
题目大意
主元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
输入
[1,2,5,9,5,9,5,5,5]
输出
5
解析
摩尔投票算法
-
维护一个候选众数
candidate和它出现的次数count。初始时candidate可以为任意值,count为0; -
遍历数组
nums中的所有元素,对于每个元素x,在判断x之前,如果count的值为 0,我们先将x的值赋予candidate,随后我们判断x:如果
x与candidate相等,那么计数器count的值增加 1;如果
x与candidate不等,那么计数器count的值减少 1。 -
在遍历完成后,
candidate即为整个数组的众数。 -
遍历数组中,
candidate出现的次数是否大于n / 2,大于返回candidate,否则返回-1。
复杂度分析
时间复杂度:
空间复杂度:
代码
int MainElement(int *A, int n) {
int count = 0;
int key = A[0];
for (int i = 0; i < n; i++) {
if (A[i] == key) {
/* code */
} else {
if (count > 0) {
count--;
} else {
key = A[i];
count = 1;
}
}
}
if (count > 0) {
for (int i = count = 0; i < n; i++) {
if (A[i] == key) {
count++;
}
}
}
if (count > n / 2) {
return key;
}
return -1;
}