Solution of O (n):
Consider saving two values when iterating over an array: One is a number in an array, and the other is the number of times. When we traverse to the next number, the number is 1 if the next number is the same as the number we saved earlier. If the next number differs from the number we saved earlier, the number is reduced by 1. If the number is zero, we need to save the next number and set the number to 1. Since the number we are looking for appears to be more than the sum of the number of other numbers appearing, the number to be searched is definitely the last number to be set at 1 o'clock.
The principle is that if there are more than half of the number of occurrences, then the number of times he will appear will definitely offset the number of occurrences of no other number. Of course, if the input example is wrong, it may pass, so the final need to check
1 BOOLG_binputinvalid =false;2 3 BOOLCheckinvalidarray (int* Numbers,intlength)4 {5G_binputinvalid =false;6 if(Numbers = = NULL && length <=0)7G_binputinvalid =true;8 9 returnG_binputinvalid;Ten } One A BOOLCheckmorethanhalf (int* Numbers,intLengthintNumber ) - { - intTimes =0; the for(inti =0; i < length; ++i) - { - if(Numbers[i] = =Number ) -times++; + } - + BOOLIsmorethanhalf =true; A if(Times *2<=length) at { -G_binputinvalid =true; -Ismorethanhalf =false; - } - - returnismorethanhalf; in } - to intMorethanhalfnum_solution2 (int* Numbers,intlength) + { - if(Checkinvalidarray (numbers, length)) the return 0; * $ intresult = numbers[0];Panax Notoginseng intTimes =1; - for(inti =1; i < length; ++i) the { + if(Times = =0) A { theresult =Numbers[i]; +Times =1; - } $ Else if(Numbers[i] = =result) $times++; - Else -times--; the } - Wuyi if(!checkmorethanhalf (numbers, length, result)) theresult =0; - Wu returnresult; -}
Interview 29: Number of occurrences in an array of more than half