
Sponsored
Sponsored
This approach leverages a hashmap to count the occurrences of each element in the input array. We iterate through the array once to populate the hashmap and then make another pass to find all elements whose count is greater than ⌊n/3⌋. While this method is straightforward and simple to implement, it uses extra space proportional to the number of unique elements.
Time Complexity: O(n), where n is the length of the array since we go through the list of numbers twice.
Space Complexity: O(n) to handle the possible maximum unique elements.
1import java.util.*;
2
3public class MajorityElement {
4 public List<Integer> majorityElement(int[] nums) {
5 Map<Integer, Integer> countMap = new HashMap<>();
6 int limit = nums.length / 3;
7 for (int num : nums) {
8 countMap.put(num, countMap.getOrDefault(num, 0) + 1);
9 }
10 List<Integer> result = new ArrayList<>();
11 for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
12 if (entry.getValue() > limit) {
13 result.add(entry.getKey());
14 }
15 }
16 return result;
17 }
18
19 public static void main(String[] args) {
20 MajorityElement me = new MajorityElement();
21 int[] nums = {3, 2, 3};
22 List<Integer> result = me.majorityElement(nums);
23 for (int num : result) {
24 System.out.print(num + " ");
25 }
26 }
27}This Java solution uses a HashMap to count the frequency of each element in the input array. We iterate over the array to populate the map. Once the map is filled, we iterate over its entries to collect keys (numbers) having values (counts) greater than ⌊n/3⌋. The HashMap enables efficient storage and lookup of key-value pairs.
The Boyer-Moore Voting Algorithm is optimized for finding the majority element which appears more than n/2 times. Here, we extend it to handle the case for n/3 by maintaining up to two potential candidates, since at most two elements can qualify for appearing more than ⌊n/3⌋ times. In the first pass, we identify the element candidates by attempting to cancel them out against others. A second pass is required to confirm the counts of these candidates to ensure they appear more than ⌊n/3⌋ times.
Time Complexity: O(n), going through elements twice.
Space Complexity: O(1) as no additional space is needed apart from variables.
This Java implementation follows Boyer-Moore logic for tracking two majority candidates with constant space, confirming by counting occurrences a second time that potential candidates truly appear >⌊n/3⌋.