Category: array
Algorithms: Boyer-Moore algorithm
- Most of the elements
Given an array of size n, the majority of the elements found therein. Most of the elements in the array refers to the number of occurrences greater than ⌊ n / 2 ⌋ elements.
You can assume that the array is non-empty, and there is always most elements of a given array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
answer
Maintain a count, most elements encountered +1, or by 1, so the final count must be positive. In iterate the process, after the encounter is cleared, re the current digital value as a candidate, re-counted.
Code
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# Boyer-Moore 算法
candi = nums[0]
count = 0
for i in nums:
if count==0:
candi=i
count += (1 if i==candi else -1)
return candi