跳轉到

Boyer-Moore Majority Voting Algorithm

The Boyer-Moore voting algorithm is one of the popular optimal algorithms which is used to find the majority element among the given elements that have more than N / 2 occurrences. This works perfectly fine for finding the majority element which takes 2 traversals over the given elements, which works in O(N) time complexity and O(1) space complexity.

// Function to find majority element
function findMajority(nums)
{
    let count = 0, candidate = -1;

    // Find majority candidate
    for (let num of nums) {
      if (count == 0) {
        candidate = num;
        count = 1;
      }
      else {
        if (num === candidate)
          count++;
        else
          count--;
      }
    }

    // Check if majority candidate occurs more than
    // n/2 times
    count = 0;
    for (let num of nums) {
      if (num === candidate)
        count++;
    }
    if (count > (nums.length / 2))
      return candidate;
    return -1;

}