Intermediate Level

Implement the method majorityElement that returns the value appearing more than half the time.

The majority element appears more than size / 2 times. The test data always contains one.

The task is designed to test careful handling of edge cases, not only the most common input.

  • Use only the first size elements.
  • Return the value, not its count.
  • A constant-memory voting scan is possible.
Example 1
Input:
nums (int[]) = [3,3,4]
size (int) = 3
Return:
(int) 3
Example 2
Input:
nums (int[]) = [2,2,1,1,1,2,2]
size (int) = 7
Return:
(int) 2
Example 3
Input:
nums (int[]) = [5]
size (int) = 1
Return:
(int) 5

Maintain a candidate and counter. Different values cancel each other until the majority candidate remains.

Run your code to see the result.