面接の質問17.10。主な要素
配列の半分以上を占める要素は、メイン要素と呼ばれます。整数配列が与えられたら、その主要な要素を見つけます。そうでない場合は、-1を返します。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums) #首先得到数组长度
unique = set(nums) #用set函数得到数组中不同元素的集合
half = int(n/2)
for i in unique: #遍历unique
if nums.count(i) > half: #如果nums中某个数大于出现次数大于一半,返回
return(i)
return(-1) #否则返回-1
ソート方法:
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
half = int(len(nums)/2)
tem_list = sorted(nums)
for i in range(half + 1):
if tem_list[i] == tem_list[i + half]:
return(tem_list[i])
return(-1)