Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from typing import List
- def boyer_moore_voting_algorithm(nums: List[int]):
- n = len(nums)
- # Step 1: Find the majority candidate
- candidate = nums[0]
- count = 1
- for i in range(1, n):
- if nums[i] == candidate:
- count += 1
- elif count == 0:
- candidate = nums[i]
- count = 1
- else:
- count -= 1
- # Step 2: Verify the majority candidate
- count = 0
- for i in range(n):
- if nums[i] == candidate:
- count += 1
- if count > n/2:
- return candidate
- else:
- return -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement