题目要求

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.

题目分析及思路

给定一个长度为n的数组,找到majority元素。定义majority元素为数组中出现次数超过⌊ n/2 ⌋次的元素。假定数组不为空且majority元素总是存在于数组中。可以先对数组进行排序,然后获取数组中间的元素(当n为奇数时获取中间元素,当n为偶数时获取中间两个元素中索引较大的那一个)

python代码

class Solution:

def majorityElement(self, nums: List[int]) -> int:

nums.sort()

return nums[len(nums)//2]

05-11 03:43