【LeetCode】229. Majority Element II

Majority Element II

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:

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

超过⌊ n/k ⌋ 最多有(k-1)个结果。k=3时最多2个结果。

因此设置两个candidate进行判断。

注意:留到最后的candidate不代表真正的结果。举例[3,2,3],2是candidate但不是结果。

class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        vector<int> ret;
        if(nums.empty())
            return ret;
        int candidate1 = nums[0];
        int count1 = 1;
        int candidate2 = nums[0];
        int count2 = 0;
        for(int i = 1; i < nums.size(); i ++)
        {
            if(count1 != 0 && count2 != 0)
            {
                if(nums[i] == candidate1)
                    count1 ++;
                else if(nums[i] == candidate2)
                    count2 ++;
                else
                {
                    count1 --;
                    count2 --;
                }
            }
            else if(count1 != 0 && count2 == 0)
            {
                if(nums[i] == candidate1)
                    count1 ++;
                else
                {
                    candidate2 = nums[i];
                    count2 = 1;
                }
            }
            else if(count1 == 0 && count2 != 0)
            {
                if(nums[i] == candidate2)
                    count2 ++;
                else
                {
                    candidate1 = nums[i];
                    count1 = 1;
                }
            }
            else
            {
                candidate1 = nums[i];
                count1 = 1;
            }
        }
        if(count1 != 0)
        {
            count1 = 0;
            for(int i = 0; i < nums.size(); i ++)
            {
                if(nums[i] == candidate1)
                    count1 ++;
            }
            if(count1 > nums.size()/3)   
                ret.push_back(candidate1);
        }
        if(count2 != 0)
        {
            count2 = 0;
            for(int i = 0; i < nums.size(); i ++)
            {
                if(nums[i] == candidate2)
                    count2 ++;
            }
            if(count2 > nums.size()/3)   
                ret.push_back(candidate2);
        }
        return ret;
    }
};

原文地址:https://www.cnblogs.com/ganganloveu/p/4630978.html