#include <iostream>
using namespace std;
int find(int* arr, int len)
{
int i = 0;
int nCnt = 0;
int nIndex = 0;
for (i = 0; i < len; i++)
{
if (nCnt == 0)
{
nIndex = arr[i];
nCnt++;
}
else
{
if (nIndex == arr[i])
nCnt++;
else
nCnt--;
}
}
return nIndex;
}
int main()
{
int test[] = {8, 1, 1, 2, 3, 4, 5, 6,
8, 8, 8, 8, 8, 8, 8, 8,};
int nLen = sizeof(test)/sizeof(test[0]);
int nResult = -1;
nResult = find(test, nLen);
cout << "Find result = " << nResult << endl;
cin >> nResult;
return 0;
}
=================================================================
#include <iostream>
using namespace std;
void debug_print(int index[], int count[])
{
for (int i = 0; i < 3; i++)
{
cout << index[i] << ":"<< count[i] << endl;
}
cout << "=====================================" << endl;
}
int check(int index[], int count[], int target)
{
int i = 0;
for (i = 0; i < 3; i++)
{
if ((index[i] == target) || (count[i] == 0))
return i;
}
return -1;
}
void find(int* arr, int len)
{
int i = 0, j = 0;
int curr = 0;
int nCnt[3] = {0,0,0};
int nIndex[3] = {0,0,0};
for (i = 0; i < len; i++)
{
if ((curr = check(nIndex, nCnt, arr[i])) != -1)
{
if ((nIndex[curr] == 0) || nCnt[curr] == 0) nIndex[curr]= arr[i];
nCnt[curr]++;
}
else
{
for (j = 0; j < 3; j++)
{
nCnt[j]--;
}
}
debug_print(nIndex, nCnt);
}
if ((nCnt[0] > 0) || (nCnt[1] > 0) || (nCnt[2] > 0))
{
cout << nIndex[0] << " "<< nIndex[1] << " "<< nIndex[2] << " " << endl;
}
else
{
cout << "None is larger than 1/4" << endl;
}
}
int main()
{
//int test[] = {1};
//int test[] = {2, 1, 1, 2, 3, 4, 3, 3, 1, 2}; // N = 10 3:3:3:1
//int test[] = {2, 1, 3, 4,}; // N = 4 1:2:3:4 a fail case
//int test[] = {1, 1, 1, 2, 4, 4, 3, 3, 1, 2,
// 2, 1, 1, 2, 3, 4, 3, 3, 1, 2,
// 2, 1, 1, 2, 3, 4, 3, 3, 1, 2}; // N = 30 10:8:8:4
int test[] = {1, 1, 1, 2, 3, 2, 1, 3, 1, 2}; // N = 10 5:3:2
int nLen = sizeof(test)/sizeof(test[0]);
find(test, nLen);
cin >> nLen;
return 0;
}