此题有多种解法,具体可以查看coder_orz的博客,
链接: https://blog.csdn.net/coder_orz/article/details/51407713
题目描述
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
给定一个长度为n的字符串,找到其中的多数元素。多数元素是出现次数超过n/2的元素。
You may assume that the array is non-empty and the majority element always exist in the array.
假定序列非空,并且主要元素总是存在的。
思路一
(HashTable)遍历数组,用一个字典记录所有出现过的元素及其个数。由于题目说明多数元素一定存在,故当找到某个元素出现次数大于 ⌊ n/2 ⌋ 时即可停止。
代码
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
digits = {}
for i in nums:
digits[i] = digits.get(i,0) + 1 #字典的get函数:返回key->键值i对应的数;如果key不存在,返回0
if digits[i] > len(nums)/2:
return i
与这个思路类似,也可以考虑用集合这一数据结构。先找出数组中的所有不同的数,相当于“取原数组的集合”的操作,然后判断该集合中的每个数在数组中出现次数是否过半。
代码(56ms)
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums_set = set(nums)
for i in nums_set:
if nums.count(i) > len(nums)/2:
return i
思路二
先对数组进行排序,排序后序列中间位置的数一定是多数元素。
代码(44ms)
nums.sort()
return nums[int(len(nums)/2)]