Repository containing solution for #SdeSheetChallenge by striver
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋
times. You may assume that the majority element always exists in the array.
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int,int> mp;
for(int x: nums) mp[x]++;
int n = nums.size()/2;
int ans = 0;
for(auto x:mp){
if(x.second>n){
ans = x.first;
return ans;
}
}
return ans;
}
};
class Solution {
public:
// moore's voting algorithm
int majorityElement(vector<int>& nums)
{
int count = 0;
int candidate = 0;
for (int x : nums) {
if (count == 0) {
candidate = x;
}
// count += (x == candidate) ? 1 : -1;
if (x == candidate) count++;
else count--;
}
return candidate;
}
};