Algorithm Puzzles: Majority Element

Algorithm Puzzles everyday every week sometimes: Majority Element

Puzzle

Puzzle from leetcode:

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.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int majorityElement(const vector<int>& nums) {
std::unordered_map<int, int> map;
int currentMajority = 0;

for(auto iter = nums.begin(); iter != nums.end(); iter++) {
map[*iter]++;
if(map[*iter] > nums.size() / 2) {
currentMajority = *iter;
break;
}
}

return currentMajority;
}
};

T.C.: O(N)
S.C.: O(N)