169. Majority Element

Description:

https://leetcode.com/problems/majority-element/#/description

Algorithm:

use mapping

Code:

class Solution {
public:
int majorityElement(vector<int>& nums) {
map <int, int> mapping;
for (int i = 0; i < nums.size();i++)
{
mapping[nums[i]]++;
}
map<int, int>::iterator it;
for (it = mapping.begin(); it != mapping.end();it++)
{
if (it->second > nums.size() / 2)
return it->first;
}
return 0;
}
};

Timing & Space:

O(n) & O(n)

Leave a Reply

Your email address will not be published. Required fields are marked *