1、某数出现频率刚好为N,出现频率最多
pre=arr[0];
count=1;
for(int i=1;i<2N;i++){
if(arr[i]==pre)count++;
else if(count>0) count--;
else {
pre=arr[i];
count++;
}
}
遍历结束后,若count==0,则arr数组的前两个不同的数中有一个是我们要找的数,若count>0,arr数组的前两个不同的数中都不是我们要找的数,直接从arr数组删除,问题降级为找出数组中出现频率超过一半的数。
2、某数出现频率刚好为N-1,出现频率最多
转载http://blog.chinaunix.net/uid-26456800-id-3383003.html
3、寻找三个数出现频率都超过了四分之一
static int candiA = 0, candiB = 0, candiC = 0;
static void FindThreeMost(int[] num)
{
int countA = 0, countB = 0, countC = 0;
for (int i = 0; i < num.Length; i++)
{
if (countA == 0 || countB == 0 || countC == 0 )
{
if (countA == 0)
{
if (countB != 0 && num[i] == candiB)
countB++;
else if (countC != 0 && num[i] == candiC)
countC++;
else
{
candiA = num[i];
countA++;
}
}
else if (countB == 0)
{
if (countA != 0 && num[i] == candiA)
countA++;
else if (countC != 0 && num[i] == candiC)
countC++;
else
{
candiB = num[i];
countB++;
}
}
else if (countC == 0)
{
if (countA != 0 && num[i] == candiA)
countA++;
else if (countB != 0 && num[i] == candiB)
countB++;
else
{
candiC = num[i];
countC++;
}
}
}
else
{
if (num[i] == candiA)
countA++;
else if (num[i] == candiB)
countB++;
else if (num[i] == candiC)
countC++;
else
{
countA--;
countB--;
countC--;
}
}
}
}
代码转自 cnblogs.com/jy02414216/archive/2011/03/04/1970497.html