关于发帖水王的求解,第一种解法是编程之美上的解法,第二种解法是寻找中位数,因为中位数必然超过一半,两种解法这里不再做解答
扩展问题很好,有3个发帖很多的ID,他们的发帖数量都超过了帖子总数目N的1/4,找出他们的ID
#include <iostream>
using namespace std;
int array[] = {1, 2, 1, 1, 2, 3, 2, 2, 3, 3, 1, 3, 4, 5, 6};
const int size = sizeof array / sizeof *array;
bool is_Error = false;
int getShuiWang(int *array, int size)
{
if (array == NULL || size <= 0)
{
is_Error = true;
return -1;
}
const int number = 3;
int candidate[number];
int times[number];
for (int i = 0; i < number; i++)
{
times[i] = 0;
}
for (int i = 0; i < size; i++)
{
bool is_In = false;
for (int j = 0; j < number; j++)
{
if (times[j] != 0)
{
if (candidate[j] == array[i])
{
times[j]++;
is_In = true;
break;
}
}
}
if (is_In == true)
continue;
is_In = false;
for (int j = 0; j < number; j++)
{
if (times[j] == 0)
{
candidate[j] = array[i];
times[j] = 1;
is_In = true;
break;
}
}
if (is_In == true)
continue;
for (int j = 0; j < number; j++)
{
times[j]--;
}
}
for (int i = 0; i < number; i++)
cout << candidate[i] << endl;
return 0;
}
void main()
{
int result = getShuiWang(array, size);
cout << "result = " << result << endl;
//return;
}