Skip to content

Commit 8032213

Browse files
committed
Solve problem '169) majority element'
1 parent f71a0a5 commit 8032213

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
Given an array `nums` of size `n`, return _the majority element_.
2+
3+
The majority element is the element that appears more than `⌊n / 2⌋` times. You may assume that the majority element always exists in the array.
4+
5+
**Example 1:**
6+
7+
```
8+
Input: nums = [3,2,3]
9+
Output: 3
10+
```
11+
12+
**Example 2:**
13+
14+
```
15+
Input: nums = [2,2,1,1,1,2,2]
16+
Output: 2
17+
```
18+
19+
**Constraints:**
20+
21+
- `n == nums.length`
22+
- `1 <= n <= 5 * 104`
23+
- `-2^31 <= nums[i] <= 2^31 - 1`
24+
25+
**Follow-up:** Could you solve the problem in linear time and in `O(1)` space?
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func main() {
6+
fmt.Println(majorityElement([]int{3, 2, 3}))
7+
fmt.Println(majorityElement([]int{2, 2, 1, 1, 1, 2, 2}))
8+
}
9+
10+
func majorityElement(nums []int) int {
11+
m := make(map[int]int)
12+
for _, v := range nums {
13+
m[v]++
14+
if m[v] > len(nums)/2 {
15+
return v
16+
}
17+
}
18+
return 0
19+
}

0 commit comments

Comments
 (0)