我正在尝试使用 Boyer 和 Moore 方法找到多数元素。程序应该要求用户在第一行输入“n”行,然后将有“n”个数字跟随“n”行作为输入。(例如:用户在第一行输入 5,然后将有 5 个数字)接下来,使用 Boyer 和 Moore 方法找到输入数组的多数元素。如果输入数组中不存在多数元素,则执行 -1。无论我输入什么输入,我的程序输出都显示为 0。请您检查并更正我的程序好吗?
输出示例:4 12 12 1 12 12 /或:3 11 2 13 -1
public static void main (String[]args)
{
int a[] = new int [1000000];
Scanner sc = new Scanner (System.in);
// User input n number of lines
int numberOfLine = sc.nextInt();
//Loop to have n elements as input
for (int i = 1; i<= numberOfLine; i++)
{
a[i] = sc.nextInt();
}
// Call method to display majority element
getMajorityElement(a);
sc.close();
}
//Method to Find M.E using Boyer & Moore approach
public static void getMajorityElement(int [] array)
{
int majorityElement = array[0];
int count = 1;
for (int index = 1; index<array.length; index++)
{
if(majorityElement==array[index])
{
count++;
}
else if(count==0)
{
majorityElement = array[index];
count = 1;
}
else
{
count --;
}
}
// Check if candidate M.E occur more than n/2 times
count = 0;
for (int index = 0; index<array.length; index++)
{
if(array[index]==majorityElement)
{
count++;
}
}
if (count > array.length/2)
{
System.out.println(majorityElement);
}
else
{
System.out.println("-1");
}
}