题目
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:
1 | Input: [3,2,3] |
Example 2:
1 | Input: [2,2,1,1,1,2,2] |
思路
Easy题打卡。因为多数元素一定存在,且个数超过总个数的一半,所以排序后中间的那个元素一定是多数元素。
代码
1 | class Solution(object): |