#include<iostream>
using namespace std;
bool isexit;
bool is_half_array(int *buff,int length,int value)
{
int i;
int count;
count = 0;
for (i = 0; i < length; i++)
{
if (value == buff[i])
count++;
}
if (count >= length / 2)
return true;
else
return false;
}
//找到这个数字:
int find_number(int *buff, int length)
{
int i;
int value;
if (buff == NULL || length <= 0)
{
isexit = false;
return -1;
}
int count = 1;
int temp = buff[0];
for (i = 1; i < length; i++)
{
if (count == 0)
{
temp = buff[i];
}
else
{
if (buff[i] == temp)
count++;
else
count--;
}
}
if (!is_half_array(buff,length,temp))
{
isexit = false;
return -1;
}
return temp;
}
//测试程序:
int main()
{
int buff[] = { 1, 5, 6, 1, 1, 2, 1, 2, 1 };
int num = sizeof(buff) / sizeof(buff[0]);
isexit = true;
int value = find_number(buff, num);
if (isexit)
{
cout << value << endl;
}
else
cout << "-1" << endl;
return 0;
}
using namespace std;
bool isexit;
bool is_half_array(int *buff,int length,int value)
{
int i;
int count;
count = 0;
for (i = 0; i < length; i++)
{
if (value == buff[i])
count++;
}
if (count >= length / 2)
return true;
else
return false;
}
//找到这个数字:
int find_number(int *buff, int length)
{
int i;
int value;
if (buff == NULL || length <= 0)
{
isexit = false;
return -1;
}
int count = 1;
int temp = buff[0];
for (i = 1; i < length; i++)
{
if (count == 0)
{
temp = buff[i];
}
else
{
if (buff[i] == temp)
count++;
else
count--;
}
}
if (!is_half_array(buff,length,temp))
{
isexit = false;
return -1;
}
return temp;
}
//测试程序:
int main()
{
int buff[] = { 1, 5, 6, 1, 1, 2, 1, 2, 1 };
int num = sizeof(buff) / sizeof(buff[0]);
isexit = true;
int value = find_number(buff, num);
if (isexit)
{
cout << value << endl;
}
else
cout << "-1" << endl;
return 0;
}