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;
}
};