Skip to content

Commit 616ef8d

Browse files
authored
feat: add function to find majority element using hashmap problem: No.169
1 parent 82e2e3e commit 616ef8d

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
func findMajorityElement(nums []int) int {
2+
// Create a hashmap to store the frequency of each element
3+
frequency := make(map[int]int)
4+
5+
// Traverse the array and count occurrences of each element
6+
for _, num := range nums {
7+
frequency[num]++
8+
}
9+
10+
// Find the element with the maximum frequency
11+
maxCount := 0
12+
var majorityElement int
13+
for num, count := range frequency {
14+
if count > maxCount {
15+
maxCount = count
16+
majorityElement = num
17+
}
18+
}
19+
20+
// Return the element with the maximum frequency (not checking n/2 times explicitly)
21+
return majorityElement
22+
}

0 commit comments

Comments
 (0)