alisadafi

Boyer-Moore-Voting

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