2

我正在尝试使用 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");
        }
}
4

1 回答 1

1

出现这种行为的原因是您的 1,000,000 个元素的数组的多数元素为零:仅设置了最初的三个或四个项目,而其余项目被零占据 - intJava 中的默认值。

通过在输入长度后分配大小来解决此问题。您还需要修复读取输入的代码,以确保数据以索引结束0..numberOfLine-1

Scanner sc = new Scanner (System.in);
// User input n number of lines
int numberOfLine = sc.nextInt();
int a[] = new int [numberOfLine];
//Loop to have n elements as input
for (int i = 0 ; i < numberOfLine ; i++) {
    a[i] = sc.nextInt();
}
于 2018-09-05T14:01:36.790 回答