您的位置:首页 > 其它

寻找多数元素

2015-08-01 16:39 232 查看
多数元素是指在数组中出现次数大于等于数组数目一半的元素,我们的算法首先得出这样一个候选元素,然后一遍扫描数组,查看是否是多数元素。

/**
*
* @author pc
*找出数组中最多的那个元素
*两种方法分为递归版与非递归版
*/
public class MAJORITY {

public static int majority(int a[]){
int count=1;
int k=0; //用来指向元素的下标
int c=a[0];//用来返回最多的那个元素
for(int j=1;j<a.length;j++){
if (count==0){
k=j;
c=a[j];
count++;
}
if(a[j]==c)
count++;
else
count--;
}
count=0;
for(int i=0;i<a.length;i++){
if(a[i]==c)
count++;
}
if(count>=a.length/2){
return c;
}
else{
return -1;
}
}

public static void main(String args[]){
int[] a={3,4,5,6,1,7,3,3,3,3};
System.out.println(majority(a));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: