diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java new file mode 100644 index 000000000..5231431e9 --- /dev/null +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java @@ -0,0 +1,34 @@ +package com.thealgorithms.datastructures.hashmap.hashing; + +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +/* +This class finds the majority element(s) in an array of integers. +A majority element is an element that appears more than or equal to n/2 times, where n is the length of the array. +*/ +public class MajorityElement { + /* + This method returns the majority element(s) in the given array of integers. + @param nums: an array of integers + @return a list of majority elements + */ + public static List majority(int[] nums){ + HashMap numToCount = new HashMap<>(); + int n = nums.length; + for (int i = 0; i < n; i++) { + if (numToCount.containsKey(nums[i])){ + numToCount.put(nums[i],numToCount.get(nums[i])+1); + } else { + numToCount.put(nums[i],1); + } + } + List majorityElements = new ArrayList<>(); + for (int key: numToCount.keySet()) { + if (numToCount.get(key) >= n/2){ + majorityElements.add(key); + } + } + return majorityElements; + } +} diff --git a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java new file mode 100644 index 000000000..45c7b6c5d --- /dev/null +++ b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java @@ -0,0 +1,49 @@ +package com.thealgorithms.datastructures.hashmap.hashing; + +import com.thealgorithms.datastructures.hashmap.hashing.MajorityElement; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.List; + +import java.util.ArrayList; + +public class MajorityElementTest{ + @Test + void testMajorityWithSingleMajorityElement() { + int[] nums = {1, 2, 3, 9, 9, 6, 7, 8, 9, 9, 9, 9}; + List expected = new ArrayList<>(); + expected.add(9); + List actual = MajorityElement.majority(nums); + assertEquals(expected, actual); + } + + @Test + void testMajorityWithMultipleMajorityElements() { + int[] nums = {1, 2, 3, 3, 4, 4, 4, 4}; + List expected = new ArrayList<>(); + expected.add(4); + List actual = MajorityElement.majority(nums); + assertEquals(expected, actual); + } + + @Test + void testMajorityWithNoMajorityElement() { + int[] nums = {1, 2, 4, 4, 5, 4}; + List expected = new ArrayList<>(); + expected.add(4); + List actual = MajorityElement.majority(nums); + assertEquals(expected, actual); + } + + @Test + void testMajorityWithEmptyArray() { + int[] nums = {}; + List expected = Collections.emptyList(); + List actual = MajorityElement.majority(nums); + assertEquals(expected, actual); + } +}