
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.
1function majorityElement(nums) {
2 const countMap = {};
3 const limit = Math.floor(nums.length / 3);
4 for (const num of nums) {
5 countMap[num] = (countMap[num] || 0) + 1;
6 }
7 return Object.keys(countMap).filter(num => countMap[num] > limit).map(Number);
8}
9
10// Example usage
11const nums = [3, 2, 3];
12console.log(majorityElement(nums));This JavaScript solution utilizes a plain object as a hashmap to count the occurrences of each number. Once the counts are recorded, an Object.keys method retrieves the keys, after which we filter based on the count being greater than ⌊n/3⌋ and map the keys back to numbers since keys are strings.
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.
using System.Collections.Generic;
public class Solution {
public IList<int> MajorityElement(int[] nums) {
int candidate1 = 0, candidate2 = 0, count1 = 0, count2 = 0;
foreach (int num in nums) {
if (num == candidate1) {
count1++;
} else if (num == candidate2) {
count2++;
} else if (count1 == 0) {
candidate1 = num;
count1 = 1;
} else if (count2 == 0) {
candidate2 = num;
count2 = 1;
} else {
count1--;
count2--;
}
}
count1 = count2 = 0;
foreach (int num in nums) {
if (num == candidate1) {
count1++;
} else if (num == candidate2) {
count2++;
}
}
IList<int> result = new List<int>();
if (count1 > nums.Length / 3) {
result.Add(candidate1);
}
if (count2 > nums.Length / 3) {
result.Add(candidate2);
}
return result;
}
public static void Main(string[] args) {
Solution sol = new Solution();
int[] nums = {3, 2, 3};
IList<int> result = sol.MajorityElement(nums);
foreach (int num in result) {
Console.Write(num + " ");
}
}
}This C# program implements Boyer-Moore logic maintaining two potential lead candidates by balancing count cycles, verifying them afterward to ensure genuine majority status.