LeetCode 169. 多数元素
题目描述
思路分析
摩尔投票法
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func majorityElement(nums []int) int {
candidate, count := 0, 0
for _, num := range nums {
if count == 0 {
candidate = num
count = 1
} else if num == candidate {
count++
} else {
count--
}
}
return candidate
}
- 时间复杂度:O (n),其中 n 是数组的长度。
- 空间复杂度:O (1),只使用了常数级别的额外空间。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
func majorityElement(nums []int) int {
candidate, count := nums[0], 1
for i := 1; i < len(nums); i++ {
if count == 0 {
candidate = nums[i]
count = 1
} else if nums[i] == candidate {
count++
} else {
count--
}
}
return candidate
}
- 时间复杂度:O(n),其中
n
是数组的长度。- 空间复杂度:O(1),只用了常数空间存储候选人和计数器。
1
write your code here
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用