面试题 收集请求k千里马

收集请求k最大值

个人信息:就读于燕大本科软件project专业 眼下大三;

本人博客:google搜索“cqs_2012”就可以;

个人爱好:酷爱数据结构和算法,希望将来从事算法工作为人民作出自己的贡献;

博客时间:2014-5-15;

编程语言:C++ ;

编程坏境:Windows 7 专业版 x64;

编程工具:vs2008;

制图工具:office 2010 powerpoint;

硬件信息:7G-3 笔记本;


真言

是问题就有方法去解决。

题目

集合里求出k个最大值。

思路

利用堆的特性去解决

建立K+1规模的小顶堆。然后不断更新堆顶,直至更新完,最后堆里除了堆顶外就是k个最大值

代码

主函数

std::pair<int *,int> KMaxOfArray(int * data,int const length,int K)
{
	// 创建k+1规模的堆
		int * pheap = new int[K+1];
		for(int i = 0;i<K+1;i++)
		{
			pheap[i] = data[i];
		}
		Heap<int>::Heap_make(pheap,K+1,Heap<int>::Heap_min);

	// 遍历整个数组。然后得到K+1个最大数
		for(int i = K+1;i<length;i++ )
		{
			pheap[0] = data[i];
			Heap<int>::Heap_downcast(pheap,0,K+1,Heap<int>::Heap_min);
		}
	// 返回结果
		return std::make_pair(pheap+1,K);
}

heap_make 函数

// 建堆操作 4
template<typename T> 
void Heap<T>::Heap_make(T *data,int const length,bool (*pf)(T,T))
{
	// 异常输入
	if( data == NULL || length < 0 )
		cout<<"异常输入"<<endl;
	else

	// 正常输入
	for(int i=0;i<length;i++)
	{
		Heap_upcast(data,i,length,pf);
	}
};

heap_downcast 函数

// 堆得下溯操作
template<typename T> 
void Heap<T>::Heap_downcast(T *data,int i,const int length,bool (*pf)(T,T))
{
	if(data != NULL && length >= 0)
	{
		T max ;
		// have two children
		while(i*2+2 <length)
		{
			max = data[i];
			//if(max >= data[i*2+1] && max >= data[2*i+2])
			if(pf(data[i*2+1],max) == false && pf(data[i*2+2],max) == false)
				break;
			// right child bigger 
			//if( data[i*2+2]>data[2*i+1] && data[i*2+2]>max)
			if(pf(data[i*2+2],data[2*i+1]) == true && pf(data[i*2+2],max) == true)
			{
				max = data[i*2+2];
				data[i*2+2] = data[i];
				data[i] = max;
				i = i*2+2;
			}
			// left child bigger
			//else if( data[i*2+1] >= data[2*i+2] && data[i*2+1]>max )
			else if(pf(data[i*2+2] ,data[2*i+1]) == false && pf(data[i*2+1],max) == true)
			{
				max = data[i*2+1];
				data[i*2+1] = data[i];
				data[i] = max;
				i = i*2+1;		
			}			
		}
		// have one child
		if(i*2+1 < length)
		{
			//if(data[i*2+1]>data[i])
			if(pf(data[i*2+1],data[i]) == true)
			{
				max = data[i*2+1];
				data[i*2+1] = data[i];
				data[i] = max;
			}
		}
	}
	else 
	{
		cout<<"exception of input Heap_downcast"<<endl;
	}
};

heap_upcast 函数

// 堆得上溯操作
template<typename T> 
void Heap<T>::Heap_upcast(T *data,int i,const int length,bool (*pf)(T,T))
{
	if(data != NULL && length >= 0)
	{
		T max ;
		// have two children
		while( (i-1)/2 >= 0 )
		{
			max = data[i];

			//if(max <= data[(i-1)/2])
			if(pf(max,data[(i-1)/2]) == false)
				break;
			// child bigger, and go up
			else 
			{
				data[i] = data[(i-1)/2];
				data[(i-1)/2] = max;

				i = (i-1)/2;
			}		
		}
	}
	else 
	{
		cout<<"exception of input Heap_downcast"<<endl;
	}
};




版权声明:本文博客原创文章,博客,未经同意,不得转载。

posted @ 2015-07-24 08:34  lcchuguo  阅读(236)  评论(0编辑  收藏  举报