Leetcode169. Majority Element
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
解法一 哈希表法
这个问题可以视为查找问题,对于查找问题往往可以使用时间复杂度为 O(1) 的哈希表,通过以空间换时间的方式进行优化。
直接遍历整个数组 ,将每一个数字(num)与它出现的次数(count)存放在哈希表中,同时判断该数字出现次数是否是最大的,动态更新 maxCount,最后输出 maxNum。
- 时间复杂度
O(n)
- 空间复杂度
O(n)
class Solution {
public int majorityElement(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
// maxNum 表示元素,maxCount 表示元素出现的次数
int maxNum = 0, maxCount = 0;
for (int num: nums) {
int count = map.getOrDefault(num, 0) + 1;
map.put(num, count);
if (count > maxCount) {
maxCount = count;
maxNum = num;
}
}
return maxNum;
}
}
解法二 位运算
把数字放眼到二进制的形式
5 5 2 1 2 2 2 都写成 2 进制
1 0 1
1 0 1
0 1 0
0 0 1
0 1 0
0 1 0
0 1 0
由于 2 是超过半数的数,它的二进制是 010,所以对于从右边数第一列一定是 0 超过半数,从右边数第二列一定是 1 超过半数,从右边数第三列一定是 0 超过半数。然后每一列超过半数的 0,1,0 用 10进制表示就是 2 。
所以我们只需要统计每一列超过半数的数,0 或者 1,然后这些超过半数的二进制位组成一个数字,就是我们要找的数。
当然,我们可以只统计 1 的个数,让每一位开始默认为 0,如果发现某一列的 1 的个数超过半数,就将当前位改为 1。
- 时间复杂度
O(n)
- 空间复杂度
O(1)
public int majorityElement(int[] nums) {
int majority = 0;
int n = nums.length;
//判断每一位
for (int i = 0, mask = 1; i < 32; i++, mask <<= 1) {
int bits = 0;
//记录当前列 1 的个数
for (int j = 0; j < n; j++) {
if ((mask & nums[j]) == mask) {
bits++;
}
}
//当前列 1 的个数是否超过半数
if (bits > n / 2) {
majority |= mask;
}
}
return majority;
}
解法三 摩尔投票法
我们假设这样一个场景,在一个游戏中,分了若干个队伍,有一个队伍的人数超过了半数。所有人的战力都相同,不同队伍的两个人遇到就是同归于尽,同一个队伍的人遇到当然互不伤害。
这样经过充分时间的游戏后,最后的结果是确定的,一定是超过半数的那个队伍留在了最后。
而对于这道题,我们只需要利用上边的思想,把数组的每个数都看做队伍编号,然后模拟游戏过程即可。
题意是寻找数组中超过一半的数字,这意味着数组中其他数字出现次数的总和都是比不上这个数字出现的次数 。即如果把 该众数记为 +1 ,把其他数记为 −1 ,将它们全部加起来,和是大于 0 的。
- 设置两个变量
candidate
和count
,candidate
用来保存数组中遍历到的某个数字,count
表示当前数字的出现次数,一开始candidate
保存为数组中的第一个数字,count
为 1 - 遍历整个数组
- 如果数字与之前
candidate
保存的数字相同,则count
加 1 - 如果数字与之前
candidate
保存的数字不同,则count
减 1 - 如果出现次数
count
变为 0 ,candidate
进行变化,保存为当前遍历的那个数字,并且同时把count
重置为 1 - 遍历完数组中的所有数字即可得到结果
- 时间复杂度
O(n)
- 空间复杂度
O(1)
class Solution {
public int majorityElement(int[] nums) {
int candidate = nums[0], count = 1;
for (int i = 1; i < nums.length; ++i) {
if (count == 0) {
candidate = nums[i];
count = 1;
} else if (nums[i] == candidate) {
count++;
} else{
count--;
}
}
return candidate;
}
}