TopcoderArchive
Archive
Algorithm problem

MajorityElement

Problem statement, definition, constraints, and public examples.

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

  1. {3, 9, 3, 3, 7}
    Returns: 3
    Element 3 occurs 3 times, which makes it a majority element of an array with 5 elements.
  2. {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.
  3. {5}
    Returns: 5
  4. {13, 13}
    Returns: 13
    All elements are equal.
  5. {249, 326, 564}
    Returns: -1
    All elements are distinct, so there is no majority element.
Back to all problems