Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- int boyer_moore_voting_algorithm(vector<int>& nums) {
- int n = nums.size();
- // Step 1: Find the majority candidate
- int candidate = nums[0];
- int count = 1;
- for (int i = 1; i < n; i++) {
- if (nums[i] == candidate) {
- count += 1;
- } else if (count == 0) {
- candidate = nums[i];
- count = 1;
- } else {
- count -= 1;
- }
- }
- // Step 2: Verify the majority candidate
- count = 0;
- for (int i = 0; i < n; i++) {
- if (nums[i] == candidate) {
- count += 1;
- }
- }
- if (count > n/2) {
- return candidate;
- } else {
- return -1;
- }
- }
- int main() {
- vector<int> nums = {2, 2, 1, 1, 1, 2, 2};
- int majority = boyer_moore_voting_algorithm(nums);
- if (majority != -1) {
- cout << "Majority element: " << majority << endl;
- } else {
- cout << "No majority element found." << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment