有一个大小为N的随机数组,找出出现次数超过N/3的数?例如:</p>
{1,2,14,12,12,15,12,12,8} the result is 12
谁有更有效的算法?我是这样做的:</p>
int getNum(int *arr, int left, int right, const int size)
{
srand(time(0));
int index = rand()%(right - left + 1) + left;
std::swap(arr[left], arr[index]);
int flag = arr[left];
int small = left;
int big = right;
int equal = left;
while(equal <= big)
{
if(arr[equal] == flag)
{
equal++;
}
else if(arr[equal] < flag)
{
swap(arr[equal++], arr[small++]);
}
else
{
while(big > equal && arr[big] > flag)
{
big--;
}
std::swap(arr[big], arr[equal]);
big--;
}
}
if(equal - small >= (size / 3))
{
return arr[small];
}
if(small - left >= size/3)
{
return getNum(arr, left, small - 1, size);
}
if(right - equal + 1 >= size/3)
{
return getNum(arr, equal, right, size);
}
else
{
return -1;
}
}
首先,我定义了三个大小相等和大的标志,选择一个数字作为标志,并找到这个数字的正确范围,当equal - small > size / 3
,这就是我们找到的数字,否则找到大小超过的边size / 3
并递归!