Skip to content

refactor: MajorityElement #6380

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -18,13 +20,18 @@ private 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) {
Expand Down
Loading