Majority Element
Given an array nums
of size n
, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋
times. You may assume that the majority element always exists in the array.
Example 1:
1 | Input: nums = [3,2,3] |
Example 2:
1 | Input: nums = [2,2,1,1,1,2,2] |
排序法:
时间复杂度:O(nlogn)
空间复杂度:O(1)
1 | class Solution { |
优化:
1 | class Solution { |
哈希表:
时间复杂度:O(n)
空间复杂度:O(n)
1 | class Solution { |
随机法:
时间复杂度:O(n)
空间复杂度:O(1)
1 | class Solution { |
分治:
时间复杂度:O(nlogn)
空间复杂度:O(logn)
1 | class Solution { |
时间复杂度:O(n)
空间复杂度:O(1)
1 | class Solution { |