[LeetCode] Top Interview 150 Problems Solving # 169 Majority Element
Understanding the Problem
It is a simple task to return the number which appears the most in the list nums. If the input is nums = [2,2,1,1,1,2,2], the number that appears the most will be 2, thus return 2.
Approach
I would first acquire the unique numbers from nums and count how many times they appear each in the list nums. Then return the number that appears in the list the most.
Solution
class Solution:
def majorityElement(self, nums: List[int]) -> int:
unique = list(set(nums))
max_num = [nums.count(i) for i in unique]
idx = max_num.index(max(max_num))
value = unique[idx]
return value
As simple as that, I would get the unique number with set() and change it to list() in case the index can be positioned randomly. Then count how many times the unique numbers appear. In the end get the majority number’s count by getting the index, then get the number from the unique with the idx, which was the result of max_num.index(max(max_num)).
Reflection
I thought there would be a better solution to this but other people also had it solved pretty much the same way. This did not take too long, as it was considered easy by LeetCode.
About the author
South Korean, master's degree of AI. A research focused AI specialist, and a rogrammer for LLM. I am seeking opportunities worldwide. I used to live in Frankfurt, Moscow, Pretoria, Baguio. Where to next?
Comments
Join the discussionNo comments yet. Be the first to comment.




