Description
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:
Input: nums = [3,2,3]
Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2
Constraints:
n == nums.length
1 <= n <= 5 * 104
-109 <= nums[i] <= 109
Follow-up: Could you solve the problem in linear time and in O(1)
space?
Code
hashmap
Time Complexity: O(N), Space Complexity: O(N)
Sorting
Time Complexity: O(NlogN), Space Complexity: O(N)
因為 majority element 佔至少 1/2,因此排在 sort 過後的 nums 的 1/2 位置的 element 一定就是 majority element。
Moore Voting Algorithm
Time Complexity: O(N), Space Complexity: O(1)
Moore Voting Algorithm 的精髓在於:刪去一個數列中的兩個不同的數字,不會影響該數列的majority element。
bit manipulation
iterate 過 32 個 bit,使用 mask 查看該位置的 bit 被設為 1 的次數是否超過一半。
注意 left shift 時,注意 mask
要設成 unsigned int
。
Source