We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 82e2e3e commit 616ef8dCopy full SHA for 616ef8d
solution/0100-0199/0169.Majority Element/Solution1.go
@@ -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