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;

}

 

}

 

posted on 2015-01-21 15:46  tneduts  阅读(147)  评论(0编辑  收藏  举报

导航