Majority Element II

Posted wxquare的学习笔记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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!
class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {

        vector<int> res;
        int m = 0, n = 0, cm = 0, cn = 0;
        for (size_t i = 0; i < nums.size(); i++) {
            if (nums[i] == m)
                cm++;
            else if (nums[i] == n)
                cn++;
            else if (cm == 0) {
                m = nums[i];
                cm++;
            } else if (cn == 0) {
                n = nums[i];
                cn++;
            } else {
                cn--;
                cm--;
            }
        }

        cm = 0;
        cn = 0;
        for (auto num : nums) {
            if (num == m) {
                cm++;
            } else if (num == n) {
                cn++;
            }
        }
        if (cm > nums.size() / 3)
            res.push_back(m);
        if (cn > nums.size() / 3)
            res.push_back(n);
        return res;
    }
};

 

以上是关于Majority Element II的主要内容,如果未能解决你的问题,请参考以下文章

Majority Element II

Majority Element II

229. Majority Element II

229. Majority Element II

LeetCode:Majority Element II

229. Majority Element II