题目描述
题目链接:https://leetcode-cn.com/problems/find-majority-element-lcci/
解题思路
第一时间想到了count
函数,Python
中的count
方法使用示例如下:
>> a = [1,2,5,9,5,9,5,5,5]
>> a.count(1)
>1
>a.count(2)
>1
>a.count(5)
>5
字符串也支持count方法
>>a = "asdasfsak"
>a.count("a")
>3
解题代码如下:
class Solution:
def majorityElement(self, nums: List[int]) -> int:
temp = len(nums)/2
for x in set(nums): # 使用set时因为只要统计一次就行,避免重复统计
if nums.count(x) > temp:
return x
return -1