leetcode python 169. 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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

题目大意:有个长度为n的数组,求出现次数最多的元素。该元素出现次数超过n/2.

思路:由于元素出现次数大于一半,因此对元素排序后n/2位置上的元素一定是要求的元素。从而只需要return sorted(nums)[len(nums)/2]即可。

下面附上我一开始写的时间复杂度为O(n*n),运行76m的代码以及discuss中利用字典的代码。

leetcode python 169. Majority Element

leetcode python 169. Majority Element