Title: Given An array of size n, find the majority element. The majority element is the element, the appears more than times ⌊ n/2 ⌋ .
Assume that the array was non-empty and the majority element always exist in the array.
1 intMajorityelement (vector<int> &num)2 {3map<int,int>m;4 intn = num.size ()/2;5 for(vector<int>::iterator it = Num.begin (); It! = Num.end (); it++)6 {7Auto ret = M.insert (Make_pair (*it,1));//for containers that do not contain duplicate keywords, the map,insert operation returns a pair8 if(!ret.second)//The firs member of the pair is an iterator that points to the element with the given keyword.9++ret.first->second;//The second member is a bool value that indicates whether the insertion of the element succeeded or already exists in the container, and if it already exists, returns bool to FalseTen One } A for(map<int,int>::iterator it = M.begin (); It! = M.end (); it++) - { - if(It->second >N) the returnIt->First ; - } -}
"Leetcode OJ" Majority Element