Advertisement
alisadafi

Boyer-Moore-Voting

Nov 9th, 2023
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.76 KB | None | 0 0
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. func boyerMooreVotingAlgorithm(nums []int) int {
  6.     n := len(nums)
  7.  
  8.     // Step 1: Find the majority candidate
  9.     candidate := nums[0]
  10.     count := 1
  11.     for i := 1; i < n; i++ {
  12.         if nums[i] == candidate {
  13.             count++
  14.         } else if count == 0 {
  15.             candidate = nums[i]
  16.             count = 1
  17.         } else {
  18.             count--
  19.         }
  20.     }
  21.  
  22.     // Step 2: Verify the majority candidate
  23.     count = 0
  24.     for i := 0; i < n; i++ {
  25.         if nums[i] == candidate {
  26.             count++
  27.         }
  28.     }
  29.  
  30.     if count > n/2 {
  31.         return candidate
  32.     } else {
  33.         return -1
  34.     }
  35. }
  36.  
  37. func main() {
  38.     nums := []int{2, 2, 1, 1, 1, 2, 2}
  39.     majority := boyerMooreVotingAlgorithm(nums)
  40.     if majority != -1 {
  41.         fmt.Println("Majority element:", majority)
  42.     } else {
  43.         fmt.Println("No majority element found.")
  44.     }
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement