refactor: MajorityElement (#6380)

* refactor: MajorityElement

* refactor: fix import ordering

---------

Co-authored-by: Deniz Altunkapan <93663085+DenizAltunkapan@users.noreply.github.com>
This commit is contained in:
Oleksandr Klymenko
2025-07-15 18:10:06 +03:00
committed by GitHub
parent 287a708c7f
commit dcb02c61df

View File

@@ -1,8 +1,10 @@
package com.thealgorithms.datastructures.hashmap.hashing;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class provides a method to find the majority element(s) in an array of integers.
@@ -18,13 +20,18 @@ public final class MajorityElement {
* Returns a list of majority element(s) from the given array of integers.
*
* @param nums an array of integers
* @return a list containing the majority element(s); returns an empty list if none exist
* @return a list containing the majority element(s); returns an empty list if none exist or input is null/empty
*/
public static List<Integer> majority(int[] nums) {
HashMap<Integer, Integer> numToCount = new HashMap<>();
if (nums == null || nums.length == 0) {
return Collections.emptyList();
}
Map<Integer, Integer> numToCount = new HashMap<>();
for (final var num : nums) {
numToCount.merge(num, 1, Integer::sum);
}
List<Integer> majorityElements = new ArrayList<>();
for (final var entry : numToCount.entrySet()) {
if (entry.getValue() >= nums.length / 2) {