数组中出现次数超过一半的数字
输入:一个数组.
输出:数组中出现次数超过一半的数字.
注:如果该数字不存在,则需对该数组进行检查,下面的程序假设所要查找的数字是存在的.
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 static int find(int *, int); 5 6 int main(int argc, char *argv[]) 7 { 8 int result; 9 int array[9] = {1,2,3,2,2,2,5,4,2}; 10 11 result = find(array, sizeof(array)/sizeof(int)); 12 13 printf("%d\n", result); 14 return 0; 15 } 16 17 static int find(int *A, int len) 18 { 19 int current, num; 20 int i; 21 22 current = A[0]; 23 num = 1; 24 25 for (i = 1; i < len; ++i) 26 { 27 if (A[i] != current) 28 { 29 if (num > 0) 30 num--; 31 else 32 { 33 num = 0; 34 current = A[i]; 35 } 36 } 37 else 38 num++; 39 } 40 41 return current; 42 }