Finding Multiple Modes In An Array

前端 未结 4 1036
醉梦人生
醉梦人生 2021-01-22 10:38

I\'m trying to write a java method which finds all the modes in an array. I know there is a simple method to find the mode in an array but when there are more than one single mo

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-22 11:09

    Hope this helps. This is my answer. Hope it helps

    public List mode(double[] m) {
        HashMap freqs = new HashMap();
        for (double d : m) {
            Double freq = freqs.get(d);
            freqs.put(d, (freq == null ? 1 : freq + 1));
        }
        List mode = new ArrayList();
        List frequency = new ArrayList();
        List values = new ArrayList();
    
        for (Map.Entry entry : freqs.entrySet()) {
            frequency.add(entry.getValue());
            values.add(entry.getKey());
        }
        double max = Collections.max(frequency);
    
        for(int i=0; i< frequency.size();i++)
        {
            double val =frequency.get(i);
            if(max == val )
            {
                mode.add(values.get(i));
            }
        }
        return mode;
    }
    

提交回复
热议问题