牛客题霸NC73数组中出现次数超过一半的数字Java题解
方法1:摩尔投票法
解题思路:假设数组首个元素为众数,遍历并统计票数,设众数的票数为1,非众数的票数为-1。当发生票数和为0时,令当前的数字为众数继续遍历数组,当遍历完数组后,最后一次被作为众数的那个数就是数组真正的众数。
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int votes = 0;
int count = 0;
int res = 0;
for(int num : array){ //遍历数组中的每个数字
if(votes == 0){ //当票数votes等于0,则将当前数字num作为众数
res = num;
}
votes+=(num==res?1:-1); //如果当前数字num等于众数,则票数votes自增1,否则票数自减1
}
for(int num :array){ //统计众数出现的次数
if(num == res){
count++;
}
}
if(count>array.length/2){ //判断众数出现的次数是否操作数组长度的一半
return res;
}else{
return 0;
}
}
}
方法2:HashMap
解题思路:利用HashMap统计数组中每个数字出现的次数,出现次数超过数组一半的那个数就是数组的众数。
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
HashMap<Integer,Integer> map = new HashMap<>();
for(int a : array){ //遍历数组array
if(!map.containsKey(a)){ //如果map中不包含值为a的key,那么将(a,1)添加到map中
map.put(a,1);
}else{ //如果map中包含值为a的key,那么将key为a的val加1
int val = map.get(a);
val++;
map.put(a,val);
}
}
for(int i:array){ //找出出现次数超过一半的数,返回
if(map.get(i)>array.length/2){
return i;
}
}
return 0;
}
}
方法3:数组排序
解题思路:将数组按从小到大的顺序排序,中间的那个数就是众数。
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
Arrays.sort(array); //将数组按从小到大的顺序排序
int res = array[array.length/2]; //位于数组中间的那个数就是众数
int count=0;
for(int i :array){ //统计众数出现的次数
if(res == i){
count++;
}
}
if(count>array.length/2){ //如果众数出现的次数超过数组长度的一半,则返回
return res;
}
return 0;
}
}