JonnyF--Majority Element
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): d = dict([]) s = len(num)/2 for i in num: if i in d: d[i] = d[i] + 1 else: d[i] = 1 if d[i] > s: return i

浙公网安备 33010602011771号