05. Majority Element II
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
Initialize variables:
n
to store the size of the input vector nums
.
Create an unordered map cnt
to store the count of occurrences of each element.
Initialize an empty vector ans
to store the majority elements.
Iterate through the nums
vector using a for loop:
Use the cnt
map to count the occurrences of each element in the nums
vector.
Iterate through the elements in the cnt
map:
Check if the count (j->second
) of an element is greater than one-third of the total elements (n/3
).
If the count meets the condition, add the element (j->first
) to the ans
vector.
After both loops have finished, the ans
vector will contain the majority elements (elements that appear more than one-third of the time) in the input vector nums
.
Return the ans
vector as the result.
Time Complexity: O(n)
Auxiliary Space Complexity: O(n)
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.