写在Java模式的方法来找到最频繁出现的元素的数组 [英] Write a mode method in Java to find the most frequently occurring element in an array

查看:145
本文介绍了写在Java模式的方法来找到最频繁出现的元素的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题云:写一个方法调用模式,返回一个整数数组中最常出现的元素。假设该阵列具有至少一个元件和所述阵列中的每个元件具有介于0和100(含)之间的值。通过选择较低的值断绝关系。

the question goes: 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.

例如,如果传递的数组包含值{27,15,15,11,27},你的方法应该返回15.(提示:你不妨看看帐簿程序从本章中获得一个想法如何解决这个问题。)

For example, if the array passed contains the values {27, 15, 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.)

下面是我的code,几乎除了工作单元素数组

Below is my code that almost works except for single-element arrays

public static int mode(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;一切正常了!

edit: finally figured it out. Changed count1 = 0; to count1 = 1; everything works now!

推荐答案

您应该使用这样的问题一个HashMap。这将需要O(n)的时间,进入的每个元素到HashMap和O(1)获取的元素。在给定的code,我基本上采取了全球最大,使之与从散'得到',每一次我进入一个元素收到的值进行比较,看看:

you should use a hashmap for such problems. it will take O(n) time to enter each element into the hashmap and o(1) to retrieve the element. In the given code, i am basically taking a global max and comparing it with the value received on 'get' from the hashmap, each time i am entering an element into it,have a look:

HashMap具有两个部分,一个是关键,第二个是值,当您在做关键get操作,返回它的值。

hashmap has two parts,one is the key, the second is the value, when you do a get operation on the key, its value is returned.

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

这篇关于写在Java模式的方法来找到最频繁出现的元素的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆