Skip to content

Commit 539b576

Browse files
committed
Add majority element
1 parent a9cc6e6 commit 539b576

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

Easy/majority-element.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
Code
2+
====
3+
4+
```go
5+
func majorityElement(nums []int) int {
6+
n := int(len(nums) / 2)
7+
8+
count := make(map[int]int, 0)
9+
10+
for _, num := range nums {
11+
if _, ok := count[num]; ok {
12+
count[num] += 1
13+
} else {
14+
count[num] = 1
15+
}
16+
}
17+
18+
for num, c := range count {
19+
if c > n {
20+
return num
21+
}
22+
}
23+
return 0
24+
}
25+
```
26+
27+
Solution in mind
28+
================
29+
30+
- Iterate through given array and keep track of count of numbers in a map (number: count).
31+
32+
- Iterate through the map and return the first number which has a number greater than floor(n/2).

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ Easy
3737

3838
- [symmetric-tree](Easy/symmetric-tree.md)
3939

40+
- [majority-element](Easy/majority-element.md)
41+
4042
Medium
4143
------
4244

0 commit comments

Comments
 (0)