Write a mode method in Java to find the most frequently occurring element in an array

前端 未结 14 2533
清酒与你
清酒与你 2020-11-29 07:17

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 le

14条回答
  •  没有蜡笔的小新
    2020-11-29 07:33

    Based on the answer from @codemania23 and the Java Docs for HashMap I wrote this code snipped and tests of a method that returns the most occurrent number in an array of numbers.

    import java.util.HashMap;
    
    public class Example {
    
        public int mostOcurrentNumber(int[] array) {
            HashMap map = new HashMap<>();
            int result = -1, max = 1;
            for (int arrayItem : array) {
                if (map.putIfAbsent(arrayItem, 1) != null) {
                    int count = map.get(arrayItem) + 1;
                    map.put(arrayItem, count);
                    if (count > max) {
                        max = count;
                        result = arrayItem;
                    }
                }
            }
    
            return result;
        }
    }
    

    Unit Tests

    import org.junit.Test;
    
    import static junit.framework.Assert.assertEquals;
    
    public class ExampleTest extends Example {
    
        @Test
        public void returnMinusOneWhenInputArrayIsEmpty() throws Exception {
            int[] array = new int[0];
            assertEquals(mostOcurrentNumber(array), -1);
        }
    
        @Test
        public void returnMinusOneWhenElementsUnique() {
            int[] array = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
            assertEquals(-1, mostOcurrentNumber(array));
        }
    
        @Test
        public void returnOne() throws Exception {
            int[] array = new int[]{0, 1, 0, 0, 1, 1, 1};
            assertEquals(1, mostOcurrentNumber(array));
        }
    
        @Test
        public void returnFirstMostOcurrentNumber() throws Exception {
            int[] array = new int[]{0, 1, 0, 1, 0, 0, 1, 1};
            assertEquals(0, mostOcurrentNumber(array));
        }
    }
    

提交回复
热议问题