From b7f22b85596349b6bffb7379401e1c479e67f021 Mon Sep 17 00:00:00 2001 From: alxkm Date: Sun, 13 Jul 2025 14:51:35 +0200 Subject: [PATCH] refactor: Mode --- .../java/com/thealgorithms/maths/Mode.java | 37 ++++++++++--------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/thealgorithms/maths/Mode.java b/src/main/java/com/thealgorithms/maths/Mode.java index f0b747cf02ec..657f8ece2a50 100644 --- a/src/main/java/com/thealgorithms/maths/Mode.java +++ b/src/main/java/com/thealgorithms/maths/Mode.java @@ -3,46 +3,49 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.List; +import java.util.Map; -/* - * Find the mode of an array of numbers - * - * The mode of an array of numbers is the most frequently occurring number in the array, - * or the most frequently occurring numbers if there are multiple numbers with the same frequency +/** + * Utility class to calculate the mode(s) of an array of integers. + *

+ * The mode of an array is the integer value(s) that occur most frequently. + * If multiple values have the same highest frequency, all such values are returned. + *

*/ public final class Mode { private Mode() { } - /* - * Find the mode of an array of integers + /** + * Computes the mode(s) of the specified array of integers. + *

+ * If the input array is empty, this method returns {@code null}. + * If multiple numbers share the highest frequency, all are returned in the result array. + *

* - * @param numbers array of integers - * @return mode of the array + * @param numbers an array of integers to analyze + * @return an array containing the mode(s) of the input array, or {@code null} if the input is empty */ public static int[] mode(final int[] numbers) { if (numbers.length == 0) { return null; } - HashMap count = new HashMap<>(); + Map count = new HashMap<>(); for (int num : numbers) { - if (count.containsKey(num)) { - count.put(num, count.get(num) + 1); - } else { - count.put(num, 1); - } + count.put(num, count.getOrDefault(num, 0) + 1); } int max = Collections.max(count.values()); - ArrayList modes = new ArrayList<>(); + List modes = new ArrayList<>(); for (final var entry : count.entrySet()) { if (entry.getValue() == max) { modes.add(entry.getKey()); } } - return modes.stream().mapToInt(n -> n).toArray(); + return modes.stream().mapToInt(Integer::intValue).toArray(); } }