http://blog.csdn.net/qq_27703417/article/details/70948850
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.
The idea of using position offensive and defensive: the first number as the first soldier, guarding the position; count = 1; encounters the same element, count++; encounters a different element, that is, the enemy, Perish, count--; When the count is 0, and the new I value as the soldiers guarding the position, continue, To the last soldier to remain in the position, there may be the main element. Add a loop and record the number of soldiers to see if they are larger than the array.
Public intMorethanhalfnum_solution (int[] Array) { intLength =Array.Length; intresult = Array[0]; intTime = 1 ; //Find the number for(inti = 1; i < length; i++) { if(0 = =Time ) {Result=Array[i]; time++ ; } Else if(Array[i] = =result) { time++; } Else{ Time-- ; } }
if (time==0) {return 0;}
// Count
int count = 0; for (int i=0;i<array.length;i++) { if(array[i]==result) { count+ +) ; } if (count>=array.length/2+1) return result; } return 0; }
Offer: A number more than half the number of occurrences in an array