LeetCode 169. 多数元素

题目描述

🔥 169. 多数元素

image-20230305170504014

思路分析

摩尔投票法

参考代码

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
}

🍏 点击查看 Java 题解

1
write your code here

相似题目

题目 难度 题解
多数元素 II Medium  
检查一个数是否在数组中占绝大多数 Easy  
本文作者:
本文链接: https://hgnulb.github.io/blog/37922469
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!