面试题29:找出数组中出现次数超过一半的数字-基于partition函数以及分摊法

本文介绍了一种使用快速排序分区思想及计数法来查找数组中出现次数超过一半的众数的有效算法。通过两种方法实现:一是基于快速排序的分区算法,二是通过遍历数组并比较元素来减少计数,最终确定众数。
<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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值