Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
本题楼主用的是哈希表的方法,根据数组中的元素建立哈希表,表中存有数组中的元素和它出现的次数,建表后查找出出现次数超过n/2的。
功能测试用例:{1,1,1,1,1,1,2,3,4,5}
特殊测试用例:{},{1}
class Solution
{
public:
int majorityElement(vector<int> &num)
{
if (num.size() == 0)
return NULL;
map<int, int> mnnNum;//建立哈希表
for (int nTemp = 0; nTemp < num.size(); nTemp++)
{
if (mnnNum.count(num[nTemp])>0)//如果存在则次数加1
{
mnnNum[num[nTemp]] += 1;
}
else
{
mnnNum.insert(pair<int, int>(num[nTemp], 1));//如果不存在则插入哈希表
}
}
map<int, int>::iterator mnniPoint;
for (mnniPoint = mnnNum.begin(); mnniPoint != mnnNum.end(); mnniPoint++)//查找出哈希表中对应出现次数超过数组长度一半的
{
if (mnniPoint->second > num.size() / 2)
{
return mnniPoint->first;
}
}
return NULL;
}
};