169. Majority Element
math
Given an array nums
of size n
, return the majority element.
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.
Example 1:
Example 2:
Constraints:
n == nums.length
1 <= n <= 5 * 10
4
-10
9
<= nums[i] <= 10
9
Follow-up: Could you solve the problem in linear time and in O(1)
space?
分析:
Boyer-Moore算法原理
直觉上: 如果一个元素超过一半,那么"抵消掉"其他元素,它还会剩下来。
步骤:
一开始没有候选人(candidate),票数是0。
遍历数组:
如果票数是0,选当前元素作为新的候选人。
如果当前元素==候选人,票数+1。
如果当前元素≠候选人,票数-1。
遍历完后,手上拿着的candidate,可能就是多数元素。
最后验证一下,真的出现了超过n/2次吗?如果是,返回candidate;否则返回-1。
Last updated
Was this helpful?