两种方法,一种通过hashMap 记录出现次数,时间空间o(n),这种方法也可以计算数组中元素出现个数等等;
还有一种投票算法,设置一个计数器和一个临时存储当前元素的变量。
1,如果count==0,则临时变量设为当前元素,count=1
2,如果临时变量与现在数组元素值相同,则count++,反之count–
3,检验value的票数是否过半
import java.util.HashMap;
import java.util.Map;
/*
* 多数投票算法
* 数组中某个数超过半数出现
* {1,2,3,2,4}这里5个数,2 只出现了2次,没有超过半数,则输出没有找到
* */
public class MajorityVote {
public static void main(String[] args) {
int [] arr={1,2,3,2,2,4,2,3,2,3,2};
//利用hashMap
System.out.println(mapMethod(arr));
System.out.print(MajVote(arr));
}
//
public static int mapMethod(int[] arr){
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
int length=arr.length;
//key值为数组值,value 值为出现的次数
for(int i=0;i<length;i++){
Integer times = map.get(arr[i]);
//如果为空,则说明该键第一次put 进map
if(times==null){
map.put(arr[i], 1);
}else {
/*
* hashMap 的put,将"key-value"值添加到hashmap 中
* 如果该key值对应的value已经存在,则用新的 value 取代旧的value
*
* */
map.put(arr[i], times+1);
}
}
//vote 是某个值出现的次数(value),freqNum 是出现次数最多的那个值
int vote=0;
int freqNum=0;
for(Map.Entry<Integer, Integer> e:map.entrySet()){
//如果有比这个次数还要多的次数,就进行替换
if(e.getValue()>vote){
freqNum = e.getKey();
vote = e.getValue();
}
}
//判断是否过半
if(vote>(length/2))
return vote;
else return -1;
}
/*
* 因为符合的众数总是存在。所以没出现一对不一样的就可以忽视这一对。我们可以用计数表示,来一个数字,
* 如果和candidate相同那么count++,
* 否则count--,如果count为零了,那么value就是下一个数。最后value就是众数了。
* */
public static int MajVote(int[] arr){
int count =0;
int value=arr[0];
int n = arr.length;
for(int i=0;i<n;i++){
if(count==0){
value=arr[i];
count=1;
}else
{
if(value==arr[i]){
count++;
}
else{
count--;
}
}
}
//检验 vlaue的个数是否过半
int test=0;
for(int i=0;i<n;i++){
if(arr[i]==value)
test++;
}
if((n/test)==1)
return test;
else return -1;
}
}
参考:
http://blog.csdn.net/shaya118/article/details/40872543
http://www.cnblogs.com/higerzhang/p/4181421.html
http://stackoverflow.com/questions/1852631/determine-the-most-common-occurance-in-an-array;
http://blog.csdn.net/haw_king/article/details/8210727#comments