在Java中编写一个模式方法来查找数组中最常出现的元素

前端之家收集整理的这篇文章主要介绍了在Java中编写一个模式方法来查找数组中最常出现的元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
问题是:

Write a method called mode that returns the most frequently occurring element of an array of integers. Assume that the array has at least one element and that every element in the array has a value between 0 and 100 inclusive. Break ties by choosing the lower value.

For example,if the array passed contains the values {27,15,11,27},your method should return 15. (Hint: You may wish to look at the Tally program from earlier in this chapter to get an idea of how to solve this problem.)

下面是我的代码几乎可以工作,除了单元素数组

publicstaticintmode(int[]n)
{
Arrays.sort(n);

    int count2 = 0;
    int count1 = 0;
    int pupular1 =0;
    int popular2 =0;


    for (int i = 0; i < n.length; i++)
    {
            pupular1 = n[i];
            count1 = 0;    //see edit

        for (int j = i + 1; j < n.length; j++)
        {
            if (pupular1 == n[j]) count1++;
        }

        if (count1 > count2)
        {
                popular2 = pupular1;
                count2 = count1;
        }

        else if(count1 == count2)
        {
            popular2 = Math.min(popular2,pupular1);
        }
    }

    return popular2;
}

编辑:终于弄清楚了.更改count1 = 0;到count1 = 1;一切都奏效了

解决方法

你应该使用hashmap来解决这个问题.将O(n)时间输入到每个元素进入hashmap和o(1)来检索元素.在给定的代码中,我基本上是采取一个全局最大值,并将其与从hashmap’get’接收的值进行比较,每当我进入一个元素时,看看:

hashmap有两个部分,一个是关键,第二个是值,当你在key上做一个get操作时,它的值被返回.

public static int mode(int []array)
    {HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
    int max=1,temp;
    for(int i=0;i<array.length;i++)
        {
            if(hm.get(array[i])!=null)
            {int count=hm.get(array[i]);
            count=count+1;
            hm.put(array[i],count);
            if(count>max)
                {max=count;
                 temp=array[i];}
            }
            else
            {hm.put(array[i],1);}
        }
        return temp;
    }
原文链接:https://www.f2er.com/java/123863.html

猜你在找的Java相关文章