我试图找出数组广告中的大多数元素,当我检查小于大小的元素时,此代码工作正常。但是只要任何元素等于数组的大小,它就会给我 arrayindexoutofbound 异常。请让我知道如何解决这个问题。
public class MajorityElement {
public static void main(String[] args) {
int a[]={2,2,7,5,2,2,6};
printMajority(a, 7);
}
//1st condition to check if element is in majority.
public static int findCandidate(int a[], int size){
int maj_index=0;
int count =1;
int i;
size=a.length;
for(i=1;i<a.length;i++ ){
if(a[maj_index]==a[i])
count++;
else
count--;
if(count==0)
{
maj_index=a[i]; //current element takes max_inex position.
count =1;
}
}
return a[maj_index];
}
public static boolean isMajority(int a[], int size, int cand){
int i, count =0;
for(i=0;i<a.length;i++)
{
if(a[i]==cand)
count++;
}
if(count>size/2){
return true;
}
else {
return false;
}
}
private static void printMajority(int a[],int size){
size=a.length;
int cand=findCandidate( a, 7);
if(isMajority(a,size,cand))
System.out.printf("%d",cand);
else
System.out.println("no such element as majority");
}
}