Suppose we have a list of numbers called nums where each number represents a vote to a candidate. We have to find the ids of the candidates that have greater than floor(n/3) votes, in non-decreasing order.
So, if the input is like nums = [3, 2, 6, 6, 6, 6, 7, 7, 7, 7, 7], then the output will be [6, 7], as 6 and 7 have 40% of the votes.
To solve this, we will follow these steps −
- ans := a new empty set
- sort the list nums
- i := 0
- n := size of nums
- while i < size of nums, do
- if occurrences of nums[i] in nums > (n / 3), then
- insert nums[i] into ans
- i := i + (n / 3)
- if occurrences of nums[i] in nums > (n / 3), then
- return ans in sorted order
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): ans = set([]) nums.sort() i = 0 n = len(nums) while i < len(nums): if nums.count(nums[i]) > n // 3: ans.add(nums[i]) i += n // 3 return sorted(list(ans)) ob = Solution() nums = [3, 2, 6, 6, 6, 6, 7, 7, 7, 7, 7] print(ob.solve(nums))
Input
[3, 2, 6, 6, 6, 6, 7, 7, 7, 7, 7]
Output
[6, 7]