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

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;

}

 

}

 

你可能感兴趣的:(element)