题目:找出数组中出现次数超过一半的元素
解法:每次删除数组中两个不同的元素,删除后,要查找的那个元素的个数仍然超过删除后的元素总数的一半
#include <stdio.h> int half_number(int a[], int n) { if( a == NULL || n <= 0 ) return -1; int i, candidate; int times = 0; for( i=0; i<n; i++ ) { if( times == 0 ) { candidate = a[i]; times = 1; } else if( a[i] == candidate ) ++times; else --times; } return candidate; } int main(void) { int a[] = {1,2,3,2,2,2,5,4,2}; int result = half_number(a, 9); if( result != -1 ) printf("%d\n", result); else printf("Error.\n"); return 0; }
该题的扩展:数组中有3个元素出现的次数都超过数组元素总数N的1/4, 找出这三个元素
解法:同上,但是每次删除4个互不相同的元素,处理上比上面的稍微麻烦
#include <stdio.h> void find(int a[], int n) { if( a==NULL || n<=3 ) { printf("Error.\n"); return ; } int i,j; int times[3] = {0,0,0}; // 3个candidate的计数 int candidate[3] = {-1,-1,-1}; // 假设元素不可能是-1 for( i=0; i<n; i++ ) { if( times[0] == 0 && a[i] != candidate[1] && a[i] != candidate[2] ) // 第1个candidate目前空缺, 且当前元素a[i]不等于其他两个candidate时, 将该元素作为新的candidate { candidate[0] = a[i]; times[0] = 1; } if( times[1] == 0 && a[i] != candidate[0] && a[i] != candidate[2] ) { candidate[1] = a[i]; times[1] = 1; } if( times[2] == 0 && a[i] != candidate[1] && a[i] != candidate[0] ) { candidate[2] = a[i]; times[2] = 1; } else if( a[i] == candidate[0] ) { ++times[0]; } else if( a[i] == candidate[1] ) { ++times[1]; } else if( a[i] == candidate[2] ) { ++times[2]; } else // 删除4个各不相同的数组元素, 删除后 { --times[0]; --times[1]; --times[2]; } } printf("%d %d %d\n",candidate[0],candidate[1],candidate[2]); } int main(void) { int a[] = {5,1,1,3,8,1,3,1,4,1,7,1,2,9,2,3,2,3,2,3,2,3,2}; find(a, 23); return 0; }