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

Find Duplicate Subtrees Problem

LeetCode 652. Given the rootof a binary tree, return all...

Delete And Earn Problem

LeetCode 740. You are given an integer array nums. You...

Degree Of An Array Problem

LeetCode 697. Given a non-empty array of non-negative integers nums,...

Custom Sort String Problem

LeetCode 791. You are given two strings order and s....

Basic Calculator IV Problem

LeetCode 770. Given an expression such as expression = “e...

Sort Characters By Frequency Problem

LeetCode 451. Given a string s, sort it in decreasing...