Skip to content

Commit dcb02c6

Browse files
refactor: MajorityElement (#6380)
* refactor: MajorityElement * refactor: fix import ordering --------- Co-authored-by: Deniz Altunkapan <[email protected]>
1 parent 287a708 commit dcb02c6

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
package com.thealgorithms.datastructures.hashmap.hashing;
22

33
import java.util.ArrayList;
4+
import java.util.Collections;
45
import java.util.HashMap;
56
import java.util.List;
7+
import java.util.Map;
68

79
/**
810
* This class provides a method to find the majority element(s) in an array of integers.
@@ -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) {

0 commit comments

Comments
 (0)