LeetCode 169. 多数元素
题目描述
思路分析
摩尔投票法
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func majorityElement(nums []int) int {
candidate, count := nums[0], 1
for i := 1; i < len(nums); i++ {
if nums[i] == candidate {
count++
} else {
count--
if count == 0 {
candidate = nums[i]
count = 1
}
}
}
return candidate
}
1
write your code here
相似题目
题目 | 难度 | 题解 |
---|---|---|
多数元素 II | Medium | |
检查一个数是否在数组中占绝大多数 | Easy |
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用