Given an array nums
of size n
, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋
times. You may assume that the majority element always exists in the array.
Input: nums = [3,2,3]
Output: 3
# dictionary for counting the elements
cnt_nums = {}
# count each element
for n in nums:
if n not in cnt_nums.keys():
cnt_nums[n] = 1
else:
cnt_nums[n] += 1
return max(cnt_nums, key=cnt_nums.get)
di.get
max(list, key=list.get)
di.get
normally used like di.get(key)
and it returns the value for the specific key. list comprehension
[k for k,v in list.items() if max(list.values())==v]
class Solution:
def majorityElement(self, nums: List[int]) -> int:
cnt_nums = {}
for n in nums:
if n not in cnt_nums.keys():
cnt_nums[n]=1
else:
cnt_nums[n]+=1
return max(cnt_nums, key=cnt_nums.get)