Find the element that appears more than half the time in a given array (guaranteed to exist). Pay attention to whether the array length is odd or even. A hash map does the job.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public :
int majorityElement ( vector < int >& nums ) {
map < int , int > m_nums ;
m_nums . clear ();
for ( int i = 0 ; i < nums . size (); i ++ )
{
auto it = m_nums . find ( nums [ i ]);
if ( it == m_nums . end ())
{
m_nums . insert ({ nums [ i ], 1 });
}
else
{
m_nums . erase ( nums [ i ]);
m_nums . insert ({ nums [ i ], ++ ( it -> second )});
}
}
for ( auto it = m_nums . begin (); it != m_nums . end (); it ++ )
{
if ( it -> second >= nums . size () / 2 + 1 )
{
return it -> first ;
}
}
}
};
Licensed under CC BY-NC-SA 4.0