所有代码均通过G++编译器测试,仅为练手纪录。
//面试题29:数组中出现次数超过一半的数字
//题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
// 例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2.
//面试题29:数组中出现次数超过一半的数字
//题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
// 例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2.
int NumPartition(int *pNum,int nSize,int nBeg,int nEnd)
{
if(NULL == pNum || nSize <= 0 || nBeg < 0 || nEnd > nSize-1)
{
return -1;
}
int index = pNum[(nBeg+nEnd)/2];
int temp = pNum[index];
pNum[index] = pNum[nEnd];
pNum[nEnd] = temp;
int nSmall = nBeg-1;
for(index = nBeg; index < nEnd; ++index)
{
if(pNum[index] < pNum[nEnd])
{
++nSmall;
if(nSmall != index)
{
temp = pNum[index];
pNum[index] = pNum[nSmall];
pNum[nSmall] = temp;
}
}
}
++nSmall;
temp = pNum[nSmall];
pNum[nSmall] = pNum[nEnd];
pNum[nEnd] = temp;
return nSmall;
}
bool CheckMoreThanHalf(int *pNum,int nSize,int nTarget)
{
int nCount = 0;
for (int i = 0; i < nSize; ++i)
{
if(pNum[i] == nTarget)
{
++nCount;
}
}
if(nCount*2 < nSize)
{
return false;
}
return true;
}
int FindNumMoreThanHalf_1(int *pNum,int nSize)
{
if(NULL == pNum || nSize <= 0)
{
return -1;
}
int nMid = nSize/2;
int nBeg = 0;
int nEnd = nSize - 1;
int index = NumPartition(pNum,nSize,nBeg,nEnd);
while (index != nMid)
{
if(index > nMid)
{
nEnd = index - 1;
index = NumPartition(pNum,nSize,nBeg,nEnd);
}
else
{
nBeg = index + 1;
index = NumPartition(pNum,nSize,nBeg,nEnd);
}
}
int nResult = pNum[nMid];
if(!CheckMoreThanHalf(pNum,nSize,nResult))
{
return -1;
}
return nResult;
}
int FindNumMoreThanHalf_2(int *pNum,int nSize)
{
if(NULL == pNum || nSize <= 0)
{
return -1;
}
int nResult = pNum[0];
int nCount = 1;
for(int i = 0; i < nSize; ++i)
{
if(0 == nCount)
{
nResult = pNum[i];
nCount = 1;
}
else if(nResult == pNum[i])
{
++nCount;
}
else
{
--nCount;
}
}
if(!CheckMoreThanHalf(pNum,nSize,nResult))
{
return -1;
}
return nResult;
}
void TestFindNumMoreThanHalf()
{
//int arrValue[] = {1,2,3,2,2,2,5,4,2};
int arrValue[] = {1,2,3,2,3,2,5,4,2};
LogInfo("FindNumMoreThanHalf:%d",FindNumMoreThanHalf_1(arrValue,sizeof(arrValue)/sizeof(int)));
LogInfo("FindNumMoreThanHalf:%d",FindNumMoreThanHalf_2(arrValue,sizeof(arrValue)/sizeof(int)));
}
ZhaiPillary
2017-01-07