Advertisement
alisadafi

Boyer-Moore-Voting

Nov 9th, 2023 (edited)
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.61 KB | None | 0 0
  1. from typing import List
  2.  
  3. def boyer_moore_voting_algorithm(nums: List[int]):
  4.     n = len(nums)
  5.  
  6.     # Step 1: Find the majority candidate
  7.     candidate = nums[0]
  8.     count = 1
  9.     for i in range(1, n):
  10.         if nums[i] == candidate:
  11.             count += 1
  12.         elif count == 0:
  13.             candidate = nums[i]
  14.             count = 1
  15.         else:
  16.             count -= 1
  17.            
  18.     # Step 2: Verify the majority candidate
  19.     count = 0
  20.     for i in range(n):
  21.         if nums[i] == candidate:
  22.             count += 1
  23.     if count > n/2:
  24.         return candidate
  25.     else:
  26.         return -1
  27.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement