LeetCode Majority Element Python

时间:2023-12-19 10:28:32

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

 class Solution:
# @param num, a list of integers
# @return an integer
def majorityElement(self, num):
dic = {}
for i in range(len(num)):
if (num[i]) not in dic:
dic[num[i]] = 1
else:
dic[num[i]] += 1
l = [(a,b) for a, b in dic.items()]
return (sorted(l,key = lambda x:x[1]))[-1][0]