描述
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.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
解析
根据定义只要个数大于 ⌊ n/2 ⌋ 的数字就是结果,所以先排序,找到 len(nums)//2 处位置的数字就是结果。
解答
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
return nums[len(nums)//2]
运行结果
Runtime: 152 ms, faster than 70.45% of Python online submissions for Majority Element.
Memory Usage: 13.3 MB, less than 82.10% of Python online submissions for Majority Element.
每日格言:过去属于死神,未来属于你自己。
感谢支持 支付宝