Write a pattern method in Java to find the most common elements in an array

The question is:

Here's my code that almost works, except for single element arrays

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

Editor: I've finally figured it out Change COUNT1 = 0; To COUNT1 = 1; Everything worked

Solution

You should use HashMap to solve this problem Input o (n) time into each element and enter HashMap and O (1) to retrieve the element In the given code, I basically take a global maximum value and compare it with the value received from HashMap 'get'. Whenever I enter an element, look at:

HashMap has two parts. One is the key and the other 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;
    }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>