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
我的思路:
这道题很简单 也有各种很简单的方法写,所以我自己在思考有没有突破点
题目说majority element的数量一定大于 [n/2] (向下取整),所以排序后的 [n/2]一定是majority element
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
return nums[int(len(nums)/2)]
不过我看了discussion大家都是这种方法哈哈哈所以思维都差不多嘛~~