www

导航

数组中出现次数超过一半的数字

public int MoreThanHalfNum_Solution(int [] array) {
if(array==null||array.length==0) return 0; int ret=array[0]; int times=1; for(int i=1; i<array.length; i++){ if(times==0){ ret=array[i]; times=1; } else { if(array[i]==ret) times++; else times--; } } int count=0; for(int i=0; i<array.length; i++){ if(array[i]==ret) count++; } if(count>array.length/2) return ret; else return 0; }

 

posted on 2019-03-01 10:08  www_practice  阅读(142)  评论(0编辑  收藏  举报