数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
限制:
1 <= 数组长度 <= 50000
代码实现1(自己通过方法):HashMap
class Solution {
public int majorityElement(int[] nums) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int length = nums.length;
for (int i = 0; i < length; i++) {
if (map.get(nums[i]) == null) {
map.put(nums[i], 1);
} else {
int count = map.get(nums[i]);
count++;
map.put(nums[i], count);
}
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
Integer key = entry.getKey();
Integer value = entry.getValue();
if (value >= length / 2) return key;
}
return -1;
}
}
代码实现2: 摩尔投票法(学到了学到了真的学到了!!)
摩尔投票法:
- 设输入数组 nums 的众数为 x ,数组长度为 n 。
- 推论一: 若记众数的票数为 +1 ,非众数的票数为 −1 ,则一定有所有数字的 票数和 >0
- 推论二: 若数组的前 a 个数字的 票数和 =0 ,则 数组剩余 (n−a) 个数字的 票数和一定仍>0,即后 (n−a)个数字的众数仍为 x
根据以上推论,记数组首个元素为n1,众数为x,遍历并统计票数。当发生票数和=0时,说明数组的众数一定不变,这是由于
- 当n1 = x:抵消的所有数字中,有一半是众数x。
- 当n1!= x::抵消的所有数字中,众数x的数量最少为0个,最多为一半。
利用此特征,每轮假设发生票数和=0 都可以缩小剩余数组区间。当遍历完成时,最后一轮假设的数字即为众数。
算法流程:
- 初始化: 票数统计 votes = 0 , 众数 x;
- 循环: 遍历数组 nums 中的每个数字 num ;
-
- 当 票数 votes 等于 0 ,则假设当前数字 num 是众数;
-
- 当 num = x 时,票数 votes 自增 1 ;当 num != x 时,票数 votes 自减 1 ;
- 返回值: 返回 x 即可;
复杂度分析:
- 时间复杂度 O(N) :N 为数组 nums 长度。
- 空间复杂度 O(1) : votes 变量使用常数大小的额外空间
class Solution {
public int majorityElement(int[] nums) {
int x = 0, votes = 0;
for(int num : nums){
if(votes == 0) x = num;
votes += num == x ? 1 : -1;
}
return x;
}
}
方法2 - 拓展
若考虑数组不存在众数 的情况,需要加入一个 “验证环节” ,遍历数组 nums 统计 x 的数量。
class Solution {
public int majorityElement(int[] nums) {
int x = 0, votes = 0, count = 0;
for(int num : nums){
if(votes == 0) x = num;
votes += num == x ? 1 : -1;
}
// 验证 x 是否为众数
for(int num : nums)
if(num == x) count++;
// 当无众数时返回 0
return count > nums.length / 2 ? x : 0;
}
}
实现代码3:排序
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}