Advertisement
alisadafi

Boyer-Moore-Voting

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