229. Majority Element II My Submissions Question

Total Accepted: 23103 Total Submissions: 91679 Difficulty: Medium

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

Hint:

How many majority elements could it possibly have?
Do you have a better hint? Suggest it!

最多只有两个候选数字。要求O(1)空间,可以分别用两个变量保存候选数字和计数,方法大致和169. Majority Element My Submissions Question
相同。代码如下:

vector<int> majorityElement(vector<int>& nums) {
    vector<int> res;
    if (nums.empty())
        return res;
        
    int cand1 = nums[0], cand2 = 0;
    int count1 = 1, count2 = 0;
    
    for (int i = 1; i < nums.size(); ++i) {   
        if (cand1 == nums[i]) {
            ++count1;
        }
        else if (cand2 == nums[i]) {
            ++count2;
        }
        else if (count1 == 0) {
            cand1 = nums[i];
            ++count1;
        }
        else if (count2 == 0) {
            cand2 = nums[i];
            ++count2;
        }     
        else {
            --count1;
            --count2;
        }
    }

    //判断候选是否满足条件
    count1 = count2 = 0;
    for (int i = 0; i < nums.size(); ++i) {
        if (cand1 == nums[i])
            ++count1;
        else if (cand2 == nums[i])
            ++count2;
    }
    if (count1 > nums.size() / 3)
        res.push_back(cand1);
    if (count2 > nums.size() / 3)
        res.push_back(cand2);

    return res;
}
原文地址:https://www.cnblogs.com/gr-nick/p/5222595.html