如果数组中多一半的数都是同一个,则称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。
示例 1:
输入:[1,2,5,9,5,9,5,5,5]
输出:5
示例 2:
输入:[3,2]
输出:-1
示例 3:
输入:[2,2,1,1,1,2,2]
输出:2
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-majority-element-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s=set(nums)
temp=int(len(nums)/2)+1
for i in s:
if nums.count(i)>=temp:
return i
return -1
执行结果:
通过
显示详情
执行用时 :28 ms, 在所有 Python 提交中击败了87.44%的用户
内存消耗 :13.9 MB, 在所有 Python 提交中击败了100.00%的用户