法1:哈希表
遍历数组,数组元素作为key,出现次数作为值,存入哈希表
遍历哈希表,若某个值大于n/2,返回其key
import java.util.HashMap;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
//哈希表
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
int n = array.length;
for(int i=0;i<n;i++){
if(!hash.containsKey(array[i])){
hash.put(array[i],1);
}else{
hash.put(array[i],hash.get(array[i])+1);
}
}
for(int key:hash.keySet()){
if(hash.get(key)>n/2)
return key;
}
return 0;
}
}
法2:投票法
具体做法:
- 初始化:候选人cond = -1, 候选人的投票次数cnt = 0
- 遍历数组,如果cnt=0, 表示没有候选人,则选取当前数为候选人,++cnt
- 否则,如果cnt > 0, 表示有候选人,如果当前数=cond,则++cnt,否则--cnt
- 直到数组遍历完毕,最后检查cond是否为众数
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
//投票法
//候选candidate为-1,候选数量count=0;
//遍历数组,若无候选,则当前为候选,候选数量count++
//若有,若当前和候选相同,则count++,否则count--
//最后验证候选是否为众数
int n =array.length;
int candidate = -1;
int count = 0;
for(int i=0;i<n;i++){
if(count==0){
candidate = array[i];
count++;
}else{
if(candidate==array[i])
count++;
else
count--;
}
}
count=0;
for(int e:array){
if(e==candidate)
count++;
}
if(count>n/2)
return candidate;
else
return 0;
}
}
法3:排序法
排序,则可能的众数必然在数组中间,验证一下是不是。