|
3 | 3 | import java.util.ArrayList; |
4 | 4 | import java.util.Collections; |
5 | 5 | import java.util.HashMap; |
| 6 | +import java.util.List; |
| 7 | +import java.util.Map; |
6 | 8 |
|
7 | | -/* |
8 | | - * Find the mode of an array of numbers |
9 | | - * |
10 | | - * The mode of an array of numbers is the most frequently occurring number in the array, |
11 | | - * or the most frequently occurring numbers if there are multiple numbers with the same frequency |
| 9 | +/** |
| 10 | + * Utility class to calculate the mode(s) of an array of integers. |
| 11 | + * <p> |
| 12 | + * The mode of an array is the integer value(s) that occur most frequently. |
| 13 | + * If multiple values have the same highest frequency, all such values are returned. |
| 14 | + * </p> |
12 | 15 | */ |
13 | 16 | public final class Mode { |
14 | 17 | private Mode() { |
15 | 18 | } |
16 | 19 |
|
17 | | - /* |
18 | | - * Find the mode of an array of integers |
| 20 | + /** |
| 21 | + * Computes the mode(s) of the specified array of integers. |
| 22 | + * <p> |
| 23 | + * If the input array is empty, this method returns {@code null}. |
| 24 | + * If multiple numbers share the highest frequency, all are returned in the result array. |
| 25 | + * </p> |
19 | 26 | * |
20 | | - * @param numbers array of integers |
21 | | - * @return mode of the array |
| 27 | + * @param numbers an array of integers to analyze |
| 28 | + * @return an array containing the mode(s) of the input array, or {@code null} if the input is empty |
22 | 29 | */ |
23 | 30 | public static int[] mode(final int[] numbers) { |
24 | 31 | if (numbers.length == 0) { |
25 | 32 | return null; |
26 | 33 | } |
27 | 34 |
|
28 | | - HashMap<Integer, Integer> count = new HashMap<>(); |
| 35 | + Map<Integer, Integer> count = new HashMap<>(); |
29 | 36 |
|
30 | 37 | for (int num : numbers) { |
31 | | - if (count.containsKey(num)) { |
32 | | - count.put(num, count.get(num) + 1); |
33 | | - } else { |
34 | | - count.put(num, 1); |
35 | | - } |
| 38 | + count.put(num, count.getOrDefault(num, 0) + 1); |
36 | 39 | } |
37 | 40 |
|
38 | 41 | int max = Collections.max(count.values()); |
39 | | - ArrayList<Integer> modes = new ArrayList<>(); |
| 42 | + List<Integer> modes = new ArrayList<>(); |
40 | 43 |
|
41 | 44 | for (final var entry : count.entrySet()) { |
42 | 45 | if (entry.getValue() == max) { |
43 | 46 | modes.add(entry.getKey()); |
44 | 47 | } |
45 | 48 | } |
46 | | - return modes.stream().mapToInt(n -> n).toArray(); |
| 49 | + return modes.stream().mapToInt(Integer::intValue).toArray(); |
47 | 50 | } |
48 | 51 | } |
0 commit comments