加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 17:48:12 所属栏目: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. Bre
问题是:

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;
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读