TopCoder problem "MajorityElement" used in TCHS SRM 41 (Division I Level One)



Problem Statement

    An array is said to have a majority element x if strictly more than half of its elements are equal to x (see examples for further clarification).



Given a int[] a, return its majority element, or -1 if it does not have one.
 

Definition

    
Class:MajorityElement
Method:findMajorityElement
Parameters:int[]
Returns:int
Method signature:int findMajorityElement(int[] a)
(be sure your method is public)
    
 

Constraints

-a will contain between 1 and 50 elements, inclusive.
-Each element of a will be between 0 and 1000, inclusive.
 

Examples

0)
    
{3, 9, 3, 3, 7}
Returns: 3
Element 3 occurs 3 times, which makes it a majority element of an array with 5 elements.
1)
    
{0, 1000, 984, 0}
Returns: -1
The number of equal elements must be strictly greater than half of array size, so 0 is not a majority element.
2)
    
{5}
Returns: 5
3)
    
{13, 13}
Returns: 13
All elements are equal.
4)
    
{249, 326, 564}
Returns: -1
All elements are distinct, so there is no majority element.

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=8137

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=10788&pm=8137

Writer:

Nickolas

Testers:

PabloGilberto , brett1479 , Olexiy , ivan_metelsky

Problem categories:

Brute Force