/*
N个元素的数组中找出出现多于N/2次的数(主元素)
问题一:如何构造一个数组,此数组中有数字出现多于N/2次?
随机生成一个数,将此数随机插入N/2+1次到数组中,其它空位再用随机生成数来填充
问题二:如果存在多于N/2次的数,如何找到它?
排序,中间的数应该是出现多于N/2次的数
*/
#include "iostream"
#include "ctime"
#include "cstdlib"
using namespace std;
#define N 10
int main()
{
int num[N] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
int index = 0; //数组下标
int count = 0; //计数
int temp;
srand((unsigned)time(0)); //播种子
int random = rand() % N; //生成10以内的数字
while(count < N/2+1) //插入N/2+1次
{
//生成某个范围内随机整数公式:rand() % (up - low + 1) + low
index = rand() % N; //随机数组下标(0~N-1)
if(num[index] != random)
{
num[index] = random;
count++;
}
}
for(int i = 0; i < N; i++) //填充未赋值的元素
{
int other = rand() % N;
if(num