Suppose we have a list of numbers called nums containing n values, where each number represents a vote to a candidate. We have to find the id of the candidate that has greater than floor(n/2) number of votes, and if there is no majority vote then return -1.
So, if the input is like nums = [6, 6, 2, 2, 3, 3, 3, 3, 3], then the output will be 3.
To solve this, we will follow these steps −
- l := size of nums
- count := a map containing each individual number and their occurrences
- for each number i and occurrence j in count, do
- if j > (l / 2), then
- return i
- if j > (l / 2), then
- return -1
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): l = len(nums) from collections import Counter count = Counter(nums) for i, j in count.items(): if j > (l // 2): return i return -1 ob = Solution() nums = [6, 6, 2, 2, 3, 3, 3, 3, 3] print(ob.solve(nums))
Input
[6, 6, 2, 2, 3, 3, 3, 3, 3]
Output
3