05. Majority Element II
The problem can be found at the following link: Question Link
My Approach
Initialize variables:
nto store the size of the input vectornums.Create an unordered map
cntto store the count of occurrences of each element.Initialize an empty vector
ansto store the majority elements.
Iterate through the
numsvector using a for loop:Use the
cntmap to count the occurrences of each element in thenumsvector.
Iterate through the elements in the
cntmap: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 theansvector.
After both loops have finished, the
ansvector will contain the majority elements (elements that appear more than one-third of the time) in the input vectornums.Return the
ansvector as the result.
Time and Auxiliary Space Complexity
Time Complexity:
O(n)Auxiliary Space Complexity:
O(n)
Code (C++)
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int n=nums.size();
unordered_map<int, int> cnt;
vector<int> ans;
for(int i=0;i<n;i++){
cnt[nums[i]]++;
}
for(auto j=cnt.begin();j!=cnt.end();j++){
if(j->second>n/3)ans.push_back(j->first);
}
return ans;
}
};
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
Was this helpful?