File tree Expand file tree Collapse file tree 1 file changed +9
-2
lines changed
src/main/java/com/thealgorithms/datastructures/hashmap/hashing Expand file tree Collapse file tree 1 file changed +9
-2
lines changed Original file line number Diff line number Diff line change 11package com .thealgorithms .datastructures .hashmap .hashing ;
22
33import java .util .ArrayList ;
4+ import java .util .Collections ;
45import java .util .HashMap ;
6+ import java .util .Map ;
57import java .util .List ;
68
79/**
@@ -18,13 +20,18 @@ private MajorityElement() {
1820 * Returns a list of majority element(s) from the given array of integers.
1921 *
2022 * @param nums an array of integers
21- * @return a list containing the majority element(s); returns an empty list if none exist
23+ * @return a list containing the majority element(s); returns an empty list if none exist or input is null/empty
2224 */
2325 public static List <Integer > majority (int [] nums ) {
24- HashMap <Integer , Integer > numToCount = new HashMap <>();
26+ if (nums == null || nums .length == 0 ) {
27+ return Collections .emptyList ();
28+ }
29+
30+ Map <Integer , Integer > numToCount = new HashMap <>();
2531 for (final var num : nums ) {
2632 numToCount .merge (num , 1 , Integer ::sum );
2733 }
34+
2835 List <Integer > majorityElements = new ArrayList <>();
2936 for (final var entry : numToCount .entrySet ()) {
3037 if (entry .getValue () >= nums .length / 2 ) {
You can’t perform that action at this time.
0 commit comments