Determine the most common occurrence in an array

前端 未结 9 973
南方客
南方客 2020-11-29 12:28

Assume I have an array of doubles that looks like the following:

Array[10] = {10, 10, 10, 3, 10, 10, 6, 10, 10, 9, 10}

I need a function th

9条回答
  •  执笔经年
    2020-11-29 13:05

    With an array of doubles this might not be easy since equality comparisons on doubles are pretty problematic. If you can get away with using integers, you can do something like the following:

        HashMap map = new HashMap();
        for(int element: Array)
        {
            Integer frequency = map.get(element);
            map.put(element, (frequency != null) ? frequency + 1 : 1);      
        }
        int mostFrequentItem  = 0;
        int[] maxFrequencies  = new int[2];
        maxFrequencies[0]     = Integer.MIN_VALUE;
    
        for(Entry entry: map.entrySet())
        {
            if(entry.getValue()>= maxFrequencies[0])
            {
                mostFrequentItem  = entry.getKey();
                maxFrequencies[1] = maxFrequencies[0];
                maxFrequencies[0] = entry.getValue();
            }
        }
        if(maxFrequencies[1] == maxFrequencies[0])
            throw new Exception();//insert whatever exception seems appropriate
                return mostFrequentItem  
    

    This will have O(n) performance, so it should be pretty optimal in asymptotic performance behaviour. If your doubles are not the results of calculations but come from an other source, that is if you can be sure that values which are basically the same will be represented equally, you might get away with using the same method for doubles, however I would still recommend being careful that this is really the case.

    Edit: some performance improvements as suggested in the comment as well as supporting checking for ambiguous case

提交回复
热议问题