[Niuke’s question] Numbers that appear more than half the time in the array

Numbers that appear more than half of the time in the array_NiukeTiba_Niuke.com

Moore voting method: Select two different numbers from the sequence and delete them each time. The last remaining number is the main element (the element with more than half the frequency). In actual implementation, a variable is used candidateto save the candidate main elements, and a counter count is used  to record candidatethe number of occurrences.

class Solution {
public:
    int MoreThanHalfNum_Solution(vector<int>& nums) {
        int candidate = -1;
        int count = 0;
        
        // 第一遍遍历,找出候选数 candidate
        for (int num : nums) {
            if (count == 0) {
                candidate = num;
                count++;
            } else {
                if (candidate == num) {
                    count++;
                } else {
                    count--;
                }
            }
        }
        
        // 第二遍遍历,验证 candidate 是否出现次数超过一半
        count = 0; // 重置计数器
        for (int num : nums) {
            if (num == candidate) {
                count++;
            }
        }
        
        if (count * 2 > nums.size()) {
            return candidate;
        } else {
            return -1; // 没有出现次数超过一半的数
        }
    }
};

Guess you like

Origin blog.csdn.net/weixin_43785314/article/details/132713500