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
sizeelements. - Return the value, not its count.
- A constant-memory voting scan is possible.
Example 1
Input
nums (int[]) =
[3,3,4]size (int) =
3Returns (int)
3Example 2
Input
nums (int[]) =
[2,2,1,1,1,2,2]size (int) =
7Returns (int)
2Example 3
Input
nums (int[]) =
[5]size (int) =
1Returns (int)
5Maintain a candidate and counter. Different values cancel each other until the majority candidate remains.
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run