一个由自然数0-1000中某些数字所组成的数组中,每个数字可能出现0次或多次,设计一个算法,找出现次数最多的数字
1,采用排序后,找出出现次数最多的数字,O(N2)
#include #include #include #include void Sort(int *pa, int sz) { int i = 0; for (i = 0; i < sz; i++) { int j = 0; for (j = 0; j < sz - 1 - i; j++) { if (pa[j]>pa[j + 1]) { int temp = pa[j]; pa[j] = pa[j + 1]; pa[j + 1] = temp; } } } } int FindRt(int *pa, int sz) { Sort(pa, sz); int i = 0; int ret = 0; int count = 1; int max = 0; for (i = 0; i < sz; i++) { if (pa[i] == pa[i + 1]) count++; else { if (count >= max) { max = count; ret = pa[i]; } count = 1; } } return ret; } int main() { int arr[] = { 1, 32, 46, 72, 45, 6, 2, 21, 532, 532, 532, 532, 532, 532, 532, 532 ,42, 43, 1, 1, 453, 41, 1, 2, 1, 53, 33, 5, 532, 324, 26, 67, 1, 1, 1, 1, 532, 532, 532, 532, 532, 532, 532 }; int sz = sizeof(arr) / sizeof(arr[0]); int ret=FindRt(arr, sz); printf("%d\n", ret); return 0; }
2,不超过N2的方法,用空间换时间
int FindRt(int *pa, int sz) { int sp[1001] = { 0 };//记录0,1,2,3,4...出现的次数 int i = 0; int max = 0; for (i = 0; i < sz; i++) { sp[pa[i]]++; } for (i = 0; i <= 1000; i++) { if (sp[i]>max) { max = sp[i]; } } for (i = 0; i <= 1000; i++) { if (sp[i] == max) { return i; } } } int main() { int arr[] = { 1, 32, 46, 72, 45, 6, 2, 21, 532, 532, 532, 532, 532, 532, 532, 532 ,42, 43, 1, 1, 453, 41, 1, 2, 1, 53, 33, 5, 532, 324, 26, 67, 1, 1, 1, 1, 532, 532, 532, 532, 532, 532, 532 }; int sz = sizeof(arr) / sizeof(arr[0]); int ret=FindRt(arr, sz); printf("%d\n", ret); return 0; }