-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathMajorityElement.java
More file actions
27 lines (22 loc) · 1.01 KB
/
MajorityElement.java
File metadata and controls
27 lines (22 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public List<Integer> majorityElement(int[] nums) {
// Create a frequency map to store the count of each element
Map<Integer, Integer> elementCountMap = new HashMap<>();
// Iterate through the input array to count element occurrences
for (int i = 0; i < nums.length; i++) {
elementCountMap.put(nums[i], elementCountMap.getOrDefault(nums[i], 0) + 1);
}
List<Integer> majorityElements = new ArrayList<>();
int threshold = nums.length / 3;
// Iterate through the frequency map to identify majority elements
for (Map.Entry<Integer, Integer> entry : elementCountMap.entrySet()) {
int element = entry.getKey();
int count = entry.getValue();
// Check if the element count is greater than the threshold
if (count > threshold) {
majorityElements.add(element);
}
}
return majorityElements;
}
}