17. Winning Vote

A class elects its representative by secret ballot. Each ballot in the array holds the ID of the student being voted for. One student is guaranteed to have received more than half of all the ballots.

Write a method majorityElement that takes the array nums of ballots and returns the ID of the student who received more than half of the votes.

Example 1

Input:
nums = [3,2,3]
Output:
3
Explanation:

Student 3 has 2 of the 3 ballots, which is more than half.

Example 2

Input:
nums = [2,2,1,1,1,2,2]
Output:
2
Explanation:

Student 2 has 4 of the 7 ballots.

Constraints

1 ≤ nums.length ≤ 1000

-109 ≤ nums[i] ≤ 109

Some value appears more than nums.length / 2 times

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…