根据我的理解,要找到多数元素 Boyer-Moore 多数投票算法是 O(1),即它是恒定的,并且与输入的大小不成比例。那么为什么 thi wiki 链接提到对数空间 {\displaystyle O(\log n)} O(\log n)
这是供参考的程序
public class MajorityElement {
/* Function to print Majority Element */
void printMajority(int a[], int size) {
/* Find the candidate for Majority */
int cand = findCandidate(a, size);
/* Print the candidate if it is Majority */
if (isMajority(a, size, cand))
System.out.println(" " + cand + " ");
else
System.out.println("No Majority Element");
}
/* Function to find the candidate for Majority */
int findCandidate(int a[], int size) {
int maj_index = 0, count = 1;
int i;
for (i = 1; i < size; i++) {
if (a[maj_index] == a[i])
count++;
else
count--;
if (count == 0) {
maj_index = i;
count = 1;
}
}
return a[maj_index];
}
/*
* Function to check if the candidate occurs more than n/2 times
*/
boolean isMajority(int a[], int size, int cand) {
int i, count = 0;
for (i = 0; i < size; i++) {
if (a[i] == cand)
count++;
}
if (count > size / 2)
return true;
else
return false;
}