Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Boyer Moore voting algorithm
- """
- Imagine removing pairs of different numbers again and again.
- Example: [2, 2, 1, 1, 2]
- First 2 stays, next 2 strengthens it, then 1 cancels one 2, next 1 cancels another 2.
- In the end, only 2 is left because it appears more times than all others.
- So the last remaining number must be the majority element.
- """
- class Solution:
- def majorityElement(self, nums: List[int]) -> int:
- num,count=0,0
- for i in nums:
- if count==0:
- num=i
- if i==num:
- count+=1
- else:
- count-=1
- return num
Advertisement
Add Comment
Please, Sign In to add comment