Skip to content

Commit dcb02c6

Browse files
refactor: MajorityElement (TheAlgorithms#6380)
* refactor: MajorityElement * refactor: fix import ordering --------- Co-authored-by: Deniz Altunkapan <93663085+DenizAltunkapan@users.noreply.github.com>
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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy