[Interview] Find more than half of the numbers in an array - Moore's voting algorithm

Moore voting algorithm

Ideas

The algorithm first takes the first element of the array as the candidate mode and sets the initial count to 1. Then, iterate through each element in the array and increment the count if the current element is equal to the candidate mode, otherwise decrement the count. When the count drops to 0, the algorithm replaces the candidate mode with the current element and resets the count. Ultimately, the candidate mode is the number that exceeds half.

principle

This algorithm works because the number of occurrences of most elements must exceed the sum of the occurrences of all other elements. By continuously canceling out different elements, the final candidate mode will be the majority element.

C++ implementation

#include <iostream>
#include <vector>

int findMajorityElement(std::vector<int>& nums) {
    
    
    int majority = nums[0];  // 候选的众数
    int count = 1;           // 候选众数的计数

    for (int i = 1; i < nums.size(); ++i) {
    
    
        if (nums[i] == majority) {
    
    
            // 如果当前元素等于候选众数,则增加计数
            ++count;
        } else {
    
    
            // 如果当前元素不等于候选众数,则减少计数
            --count;
            if (count == 0) {
    
    
                // 当计数降为0时,更换候选众数为当前元素
                majority = nums[i];
                count = 1;
            }
        }
    }

    // 最终的候选众数即为超过一半的数
    return majority;
}

int main() {
    
    
    std::vector<int> nums = {
    
    2, 2, 1, 1, 1, 2, 2};
    int majorityElement = findMajorityElement(nums);
    std::cout << "Majority Element: " << majorityElement << std::endl;
    return 0;
}

the complexity

The time complexity of Moore's voting algorithm is O(n), where n is the length of the array, because it only needs to traverse the array once. This makes it an efficient way to find the most elements in large data sets.

Guess you like

Origin blog.csdn.net/weixin_36313227/article/details/133270790