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

Merged
merged 5 commits into from
Jul 15, 2025
Merged
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
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