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.
Idea: If there is more than half the number of occurrences of an array, there must be two equal numbers attached. If we remove the unequal numbers that are attached, the rest is equal.
Public intMorethanhalfnum_solution (int[] Array) { inti; if(Array.Length = = 1)returnArray[0]; if(Array.Length = = 0)return0; for(i=0;i<= (array.length-1)/2;i=i+2){ if(array[i]==array[i+1]){ Break; } } if(i<= (array.length-1)/2){ returnArray[i]; }Else{ if(Array[i] = = Array[i-1]){ returnArray[i]; }Else{ return0; } } }
Another type of code is:
Public intMorethanhalfnum_solution (int[] Array) { intCount = 0; inttemp = 0; for(inti=0;i<array.length;i++){ if(count = = 0) {Temp=Array[i]; Count=1; }Else{ if(Array[i] = =temp) {Count++; }Else{Count--; } } } intnum = 0; for(inti=0;i<array.length;i++){ if(Array[i] = =temp) {num++; } } if(Num> (ARRAY.LENGTH/2)){ returntemp; }Else{ return0; } }
Number of occurrences more than half in an array