publicclassSolution {
public List<Integer>majorityElement(int[] nums) {
Map<Integer, Integer> countMap =new HashMap<>();
// Count the occurrences of each elementfor (int num : nums) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
List<Integer> result =new ArrayList<>();
int threshold = nums.length/ 3;
// Collect the elements that appear more than n/3 timesfor (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
if (entry.getValue() > threshold) {
result.add(entry.getKey());
}
}
return result;
}
publicstaticvoidmain(String[] args) {
Solution solution =new Solution();
int[] nums = {3, 2, 3};
System.out.println(solution.majorityElement(nums)); // Output: [3]int[] nums2 = {1, 1, 1, 3, 3, 2, 2, 2};
System.out.println(solution.majorityElement(nums2)); // Output: [1, 2] }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defmajorityElement(self, nums):
count_map = {}
# Count the occurrences of each elementfor num in nums:
count_map[num] = count_map.get(num, 0) +1 result = []
threshold = len(nums) //3# Collect the elements that appear more than n/3 timesfor num, count in count_map.items():
if count > threshold:
result.append(num)
return result