Title Description
If there is a number in the array that appears more than half the length of the array, 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. Output 0 If it does not exist.
Train of thought 1: Time complexity Nlogn
Sorted first.
If the condition is met, the number must be in the middle of the array.
Also determine whether the number of occurrences equal to the middle position is greater than half the length of the array.
1 Importjava.util.Arrays;2 Public classSolution {3 Public intMorethanhalfnum_solution (int[] Array) {4 Arrays.sort (array);5 for(inti=array.length/4;i<array.length*3/4;i++)6 if(ARRAY[I]!=ARRAY[ARRAY.LENGTH/2])7 return0;8 returnArray[array.length/2];9 }Ten One}
Idea 2:0 (N)
There is a number in the array that occurs more than half the length of the array, which means that it appears more often than any other number. So when we iterate over the array, we save 2 values, one is a number in the array,
One is the number of times. When we traverse to the next number, if it is the same as the current number, the number of times plus one, if different, the number minus one. When the number of times becomes 0, reassign a number.
1 Public classSolution {2 Public intMorethanhalfnum_solution (int[] a) {3 intVal=a[0],cnt=1;4 for(inti=1;i<a.length;i++){ 5 if(cnt==0){6Cnt=1;7Val=A[i];8 }9 Else if(Val==a[i]) cnt++;Ten Elsecnt--; One } A for(inti=0;i<a.length;i++) - if(A[i]==val) cnt++; - returncnt>a.length/2?val:0; the } -}
28 occurrences of more than half of the number in an array