AgPro

导航

最大间隙问题--线性时间实现

#include <iostream>
using namespace std;

const int MAX_SIZE = 100;
double x[MAX_SIZE];
int n;

int mini()
{
	int k=1;
	double temp = x[k];	
	for ( int i=2; i<=n; i++ )
	{
		if ( x[i]<temp )
		{
			temp = x[i];
			k = i;
		}
	}
	return k;
}

int maxi()
{
	int k=1;
	double temp = x[k];	
	for ( int i=2; i<=n; i++ )
	{
		if ( x[i]>temp )
		{
			temp = x[i];
			k = i;
		}
	}
	return k;
}

double maxgap()
{
	double minx = x[mini()];
	double maxx = x[maxi()];

	int *count = new int[n+1];
	double *low = new double[n+1];
	double *high = new double[n+1];
	int i;

	for ( i=1; i<=n; i++ )
	{
		count[i] = 0;
		high[i] = minx;
		low[i] = maxx;
	}

	for ( i=1; i<=n; i++ )
	{
		int bucket = int((n-1)*(x[i]-minx)/(maxx-minx))+1;//n个数放于n-1个盒子中
		count[bucket]++;
		if (x[i]<low[bucket])
			low[bucket] = x[i];
		if (x[i]>high[bucket])
			high[bucket] = x[i];
	}

	double left = high[1];
	double gap;
	double max=0;
	//鸽笼原理,至少一个桶为空
	//则最小gap不可能出现在同一个桶里,只可能出现在桶间
	for ( i=2; i<=n; i++ )
	{
		if ( count[i] )
		{
			gap = low[i] - left;
			if ( gap>max )
				max = gap;
			left = high[i];
		}
	}
	return max;
}


int main()
{
	cin >> n;
	int i;
	for ( i=1; i<=n; i++ )
		cin >> x[i];
	cout << maxgap() << endl;

	return 0;
}

posted on 2010-06-11 09:41  AgPro  阅读(636)  评论(0编辑  收藏  举报