2 minutes
Leetcode 229
This solution is pretty simple:
- We loop through
nums
- We add
1
to a map of integers calledm
, so we add1
tom[num]
wherenum
is the current number innums
. - Then we check whether
m[num] == len(nums) / 3 + 1
this is checking whether the element is a majority element.
Note: We can’t do m[num] >= len(nums) / 3 + 1
. This can be shown with an example:
If we have the example nums = [1, 2, 1, 1, 1]
, and we have the expected output of res = [1]
, it won’t work because we can:
- First add one to
m[1]
som = [1 : 1]
- Then add one to
m[2]
som = [1 : 1, 2 : 1]
- Then add one to
m[1]
som = [1 : 2, 2 : 1]
, since5 / 3 == 1
,m[1] = 2
, and2 > 1
. We can append1
tores
, sores = [1]
. - Then add one to
m[1]
som = [1 : 3, 2 : 1]
, since5 / 3 == 1
,m[1] = 3
, and3 > 1
. We can append1
tores
, sores = [1, 1]
. - Then add one to
m[1]
som = [1 : 4, 2 : 1]
, since5 / 3 == 1
,m[1] = 4
, and4 > 1
. We can append1
tores
, sores = [1, 1, 1]
.
Since res = [1, 1, 1]
we can see how it is not the expected output of res = [1]
.
The Code:
func majorityElement(nums []int) []int {
m := make(map[int] int)
res := []int{}
for _, num := range nums {
m[num]++
if m[num] == len(nums)/3 + 1 {
res = append(res, num)
}
}
return res
}
Read other posts