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.
Ideas:
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 all other numbers appear. So we can 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, minus 1 if the next number differs from the number we saved earlier. 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.
int morethanhalfnum (int *numbers, int length) {if (Checkinvalidarray (numbers,length)) return 0;int result=numbers[0]; int times=1;for (int i=1; i<length; i++) {if (times==0) {Result=numbers[i];times=1;} else if (Result==numbers[i]) {times++;} else{times--;}} if (! Checkmorethanhalf (Numbers,length,result)) {result=0;} return result;} Check that the input parameters are reasonable bool G_inputinvalid=false;bool checkinvalidarray (int *numbers, int length) {g_inputinvalid=false;if ( numbers==null| | length<=0) {g_inputinvalid=true;} return g_inputinvalid;} Check if the result is reasonable bool Checkmorethanhalf (int *numbers, int length, int number) {///count int times=0;for (int i=0; i<length; i++) {if (Numbers[i]==number) {times++;}} BOOL Ismorethanhalf=true;if (times*2<=length) {g_inputinvalid=true;ismorethanhalf=false;} return ismorethanhalf;}
Number of occurrences more than half in an array