Majority Element II Problem


Description

LeetCode Problem 229.

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

Example 1:

1
2
Input: nums = [3,2,3]
Output: [3]

Example 2:

1
2
Input: nums = [1]
Output: [1]

Example 3:

1
2
Input: nums = [1,2]
Output: [1,2]

Constraints:

  • 1 <= nums.length <= 5 * 10^4
  • -10^9 <= nums[i] <= 10^9


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        int s = nums.size();
        
        map<int, int> counter;
        for(int i = 0; i < s; i++)
        {
            counter[nums[i]]++;
        }
        
        vector<int> result;
        for(auto i : counter)
        {
            if(i.second > s / 3)
            {
                result.push_back(i.first);
            }
        }
        
        return result;
    }
};




Related Posts

X Of A Kind In A Deck Of Cards Problem

LeetCode 914. In a deck of cards, each card has...

Word Subsets Problem

LeetCode 916. You are given two string arrays words1 and...

Vowel Spellchecker Problem

LeetCode 966. Given a wordlist, we want to implement a...

Verifying An Alien Dictionary Problem

LeetCode 953. In an alien language, surprisingly, they also use...

Unique Morse Code Words Problem

LeetCode 804. International Morse Code defines a standard encoding where...

Unique Email Addresses Problem

LeetCode 929. Every valid email consists of a local name...