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