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 1
1
package com .thealgorithms .datastructures .hashmap .hashing ;
2
2
3
3
import java .util .ArrayList ;
4
+ import java .util .Collections ;
4
5
import java .util .HashMap ;
5
6
import java .util .List ;
7
+ import java .util .Map ;
6
8
7
9
/**
8
10
* This class provides a method to find the majority element(s) in an array of integers.
@@ -18,13 +20,18 @@ private MajorityElement() {
18
20
* Returns a list of majority element(s) from the given array of integers.
19
21
*
20
22
* @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
22
24
*/
23
25
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 <>();
25
31
for (final var num : nums ) {
26
32
numToCount .merge (num , 1 , Integer ::sum );
27
33
}
34
+
28
35
List <Integer > majorityElements = new ArrayList <>();
29
36
for (final var entry : numToCount .entrySet ()) {
30
37
if (entry .getValue () >= nums .length / 2 ) {
You can’t perform that action at this time.
0 commit comments