Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import "fmt"
- func boyerMooreVotingAlgorithm(nums []int) int {
- n := len(nums)
- // Step 1: Find the majority candidate
- candidate := nums[0]
- count := 1
- for i := 1; i < n; i++ {
- if nums[i] == candidate {
- count++
- } else if count == 0 {
- candidate = nums[i]
- count = 1
- } else {
- count--
- }
- }
- // Step 2: Verify the majority candidate
- count = 0
- for i := 0; i < n; i++ {
- if nums[i] == candidate {
- count++
- }
- }
- if count > n/2 {
- return candidate
- } else {
- return -1
- }
- }
- func main() {
- nums := []int{2, 2, 1, 1, 1, 2, 2}
- majority := boyerMooreVotingAlgorithm(nums)
- if majority != -1 {
- fmt.Println("Majority element:", majority)
- } else {
- fmt.Println("No majority element found.")
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement