【LeetCode OJ】Majority Element

时间:2022-02-11 08:46:15

题目: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.

 int majorityElement(vector<int> &num)
{
map<int, int> m;
int n = num.size() / ;
for (vector<int>::iterator it = num.begin(); it != num.end(); it++)
{
auto ret = m.insert(make_pair(*it, )); //对于不包含重复关键字的容器map,insert操作返回一个pair
if (!ret.second) //pair的firs成员是一个迭代器,指向具有给定关键字的元素,
++ret.first->second;//second成员是一个bool值,指出元素的插入成功还是已经存在于容器中,如果已存在,则返回bool为false }
for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
{
if (it->second > n)
return it->first;
}
}