check the element in the array occurs more than half of the array length

时间:2022-09-20 12:20:55

Learn this from stackflow.

public class test {

public static void main(String[] args) throws IOException

{

int [] a={1,2,3,4,4,4,5,4,4};

int r=GetMajorElement(a);

System.out.println(r);

}

//check the element in the array occurs more than half of the array length

public static int GetMajorElement(int[] a)

{

int r=a[0];

int count=1;

for(int i=1;i<a.length;i++)

{

if(r==a[i])

count++;

else count--;

if(count==0)

{        r=a[i]; count++;}

}

return r>=a.length/2?r:-1;

}

}