05. Majority Element II
The problem can be found at the following link: Question Link
My Approach
Initialize variables:
n
to store the size of the input vectornums
.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 thenums
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 theans
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 vectornums
.Return the
ans
vector as the result.
Time and Auxiliary Space Complexity
Time Complexity:
O(n)
Auxiliary Space Complexity:
O(n)
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. 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 rishabhv12/Daily-Leetcode-Solution repository.
Last updated