
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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public IList<int> MajorityElement(int[] nums) {
6 Dictionary<int, int> countMap = new Dictionary<int, int>();
7 int limit = nums.Length / 3;
8 foreach (int num in nums) {
9 if (!countMap.ContainsKey(num)) {
10 countMap[num] = 0;
11 }
12 countMap[num]++;
13 }
14 IList<int> result = new List<int>();
15 foreach (var entry in countMap) {
16 if (entry.Value > limit) {
17 result.Add(entry.Key);
18 }
19 }
20 return result;
21 }
22
23 public static void Main(string[] args) {
24 Solution sol = new Solution();
25 int[] nums = {3, 2, 3};
26 IList<int> result = sol.MajorityElement(nums);
27 foreach (int num in result) {
28 Console.Write(num + " ");
29 }
30 }
31}This C# implementation uses a Dictionary to count occurrences of elements in the array. After populating the dictionary with counts, the code checks each element's count to determine if it appears more than ⌊n/3⌋ times and adds it to the result list.
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 C program applies Boyer-Moore to locate up to two potential majority elements. Initial counts start at zero, and when a candidate is different, the count decreases. If zeroed, a new candidate is established. A further check verifies that these candidates surpass ⌊n/3⌋ occurrences.