LeetCode Majority Element Python

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.

 

 

 1 class Solution:
 2     # @param num, a list of integers
 3     # @return an integer
 4     def majorityElement(self, num):
 5         dic = {}
 6         for i in range(len(num)):
 7             if (num[i]) not in dic:
 8                 dic[num[i]] = 1
 9             else:
10                 dic[num[i]] += 1
11         l = [(a,b) for a, b in dic.items()]
12         return (sorted(l,key = lambda x:x[1]))[-1][0]
13         

 

posted @ 2015-03-27 10:00  繁星苑  阅读(125)  评论(0编辑  收藏  举报