<span style="font-size:14px;">#include <iostream>
using namespace std;
int partition( int a[], int low, int high )
{
if( low >= high )
{
return low;
}
int index = low - 1;
for( int i = low, j = high; i < j; ++i )
{
if( a[i] < a[high] )
{
index++;
if( index != i )
{
int tmp = a[i];
a[i] = a[index];
a[index] = tmp;
}
}
}
index++;
int tmp = a[index];
a[index] = a[high];
a[high] = tmp;
return index;
}
int getMoreThanHalfNum_byPartition( int a[], int low, int high )
{
int result = -1;
if( NULL == a || low > high )
{
cout << "getMoreThanHalfNum_byPartition func: err -1, NULL == a || low > high" << endl;
return result;
}
if( low == high )
{
result = a[low];
return result;
}
int low1 = low;
int high1 = high;
int n = high - low + 1; // 数组a元素个数
int idx = partition( a, low, high );
int mid = n >> 1;
while( idx != mid )
{
if( idx < mid )
{
low = idx + 1;
// cout << low << ' ' << high << endl;
idx = partition( a, low, high );
// getchar();
}
else
{
high = idx - 1;
// cout << low << ' ' << high << endl;
idx = partition( a, low, high );
// getchar();
}
}
result = a[mid];
int times = 0; // 判断是否有该数
for( int i = low1; i <= high1; ++i )
{
if( a[i] == result )
{
times++;
}
}
if( times *2 <= n )
{
cout << "getMoreThanHalfNum_byPartition func: err: no this number, times *2 <= n " << endl;
result = -1;
}
return result;
}
// 用cnt和result保存当前result已经出现的次数和result,当出现不同时,就减少次数,自我感觉有点像分摊
int getMoreThanHalfNum( int a[], int low, int high )
{
int result = -1;
if( NULL == a || low > high )
{
cout << "getMoreThanHalfNum func: err -1, NULL==a || low > high " << endl;
return result;
}
if( low == high )
{
result = a[low];
return result;
}
result = a[low];
int cnt = 1;
for( int i = low + 1; i <= high; i++ )
{
if( 0 == cnt )
{
cnt = 1;
result = a[i];
}
else if( a[i] != result )
{
cnt--;
}
else if( a[i] == result )
{
cnt++;
}
}
int times = 0; // 判断是否有该数
for( int i = low; i <= high; ++i )
{
if( a[i] == result )
{
times++;
}
}
if( times *2 <= high - low + 1 )
{
cout << "getMoreThanHalfNum_byPartition func: err: no this number, times *2 <= n " << endl;
result = -1;
}
return result;
}
int main()
{
int ret = 0;
int a[] = { 1, 2, 3, 2, 2, 2, 5, 4, 2 };
cout << getMoreThanHalfNum( a, 0, 8 ) << endl; // 2
cout << getMoreThanHalfNum_byPartition( a, 0, 8 ) << endl; // 2
cout << endl;
return ret;
}</span>面试题29:找出数组中出现次数超过一半的数字-基于partition函数以及分摊法
最新推荐文章于 2023-08-06 10:20:48 发布
本文介绍了一种使用快速排序分区思想及计数法来查找数组中出现次数超过一半的众数的有效算法。通过两种方法实现:一是基于快速排序的分区算法,二是通过遍历数组并比较元素来减少计数,最终确定众数。

2万+

被折叠的 条评论
为什么被折叠?



