//============================================================================ // Name : Tango.cpp // Author : qibaoyuan // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; void find_num(int a[], int length, const int m); int main() { int a[] = { 1, 2, 2, 21, 1, 1, 1, 2, 2, 1, 1, 1, 1 }; find_num(a, sizeof(a) / sizeof(a[0]), 56); return 0; } void find_num(int a[], int length, const int m) { int *result = new int[m - 1];//存放前m-1个id int *count = new int[m - 1];//存放计数 int i = 0; for (i = 0; i < m - 1; i++) { result[i] = a[i]; count[i] = 1; } bool found; int j; for (; i < length; i++) { found = false; //找到id,计数加1 for (j = 0; j < m - 1; j++) { if (a[i] == result[j]) { count[j]++; found = true; break; } } //未找到id,如果未满则插入 if (!found) { j = 0; for (; j < m - 1; j++) { if (count[j] == 0) {//未满 result[j] = a[i]; count[j] = 1; found = true; break; } } } //未找到id,且满了,则每个数少1 if (!found) { j = 0; for (; j < m - 1; j++) { count[j]--; } } } //验证 int *count2 = new int[m - 1]; for (i = 0; i < m - 1; i++) count2[i] = 0; for (i = 0; i < length; i++) for (j = 0; j < m - 1; j++) if (count[j] > 0 && result[j] == a[i]) { count2[j]++; break; } for (i = 0; i < m - 1; i++) if (count2[i] > length / m) cout << result[i] << " "; cout << endl; }