Title: There is a number in the array that appears more than half the length of the array, please find this number. For example, enter an array of length 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears in the array 5 times, which exceeds half the length of the array, the output is 2.
Public classmorethanhalf{ Public intGetmorethanhalf (int[] Array) { if(array==NULL|| array.length==0)return-1; intresult = Array[0]; intCount = 0; for(inti=0;i<array.length;i++){ if(Count ==0) {result=Array[i]; Count= 1; }Else if(Result = =Array[i]) {Count++; }Else{Count--; }} Count= 0; for(inti=0;i<array.length;i++){ if(Result = =Array[i]) {Count++; } } if(Count > (ARRAY.LENGTH/2)){ returnresult; } return-1; } Public Static voidMain (string[] args) {int[] Array = {1,2,3,2,2,2,5,4,2}; Morethanhalf m=Newmorethanhalf (); intresult =m.getmorethanhalf (array); SYSTEM.OUT.PRINTLN (result); }}
Number of occurrences more than half in an array