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 / 2的元素,之前看过一种解题方法:用两个标记量,一个标记元素的值,一个标记出现次数,遍历数组,如果新元素与标记元素相等,则标记次数递增,否则标记次数减一,当次数为0时,将新元素赋值为标记元素,出现次数重置为1,最后得到的标记元素就是出现次数 > n / 2的元素。这种解法的缺点就是必须要求数组中有出现频率超过 n /2。
class Solution:
# @param {integer[]} nums
# @return {integer}
def majorityElement(self, nums):
if len(nums) < 1:
return -1
maj_val = nums[0]
maj_cnt = 1
for i in range(len(nums)):
if nums[i] == maj_val:
maj_cnt += 1
else:
maj_cnt -= 1
if 0 == maj_cnt:
maj_val = nums[i]
maj_cnt = 1
return maj_val