Skip to content

Commit 65552da

Browse files
committed
Add solution and README for problem 169
1 parent 6e07ff8 commit 65552da

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# [169.Majority Element][title]
2+
3+
## Description
4+
Given an array `nums` of size `n`, return the majority element.
5+
6+
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.
7+
8+
**Example 1:**
9+
10+
```
11+
Input: nums = [3,2,3]
12+
Output: 3
13+
```
14+
15+
**Example 2:**
16+
17+
```
18+
Input: nums = [2,2,1,1,1,2,2]
19+
Output: 2
20+
```
21+
22+
## 结语
23+
24+
如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me]
25+
26+
[title]: https://leetcode.com/problems/majority-element/
27+
[me]: https://github.com/kylesliu/awesome-golang-algorithm

leetcode/101-200/0169.Majority-Element/Solution.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,20 @@ func majorityElement_3(nums []int) int {
4949

5050
return majorityElement_3(numsTmp)
5151
}
52+
53+
func majorityElement_4(nums []int) int {
54+
times := 1
55+
target := nums[0]
56+
for idx := 1; idx < len(nums); idx++ {
57+
if nums[idx] == target {
58+
times++
59+
continue
60+
}
61+
times--
62+
if times == 0 {
63+
target = nums[idx]
64+
times = 1
65+
}
66+
}
67+
return target
68+
}

leetcode/101-200/0169.Majority-Element/Solution_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ var SolutionFuncList = []SolutionFuncType{
1717
majorityElement_1,
1818
majorityElement_2,
1919
majorityElement_3,
20+
majorityElement_4,
2021
}
2122

2223
// Test case info struct

0 commit comments

Comments
 (0)