//桶排序计算最大间距
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct tagBucket
{
int nMin;
int nMax;
bool isValid;
tagBucket():isValid(false){};
void add_(int val)
{
if(isValid)
{
if(val<nMin)
nMin=val;
if(val>nMax)
nMax=val;
}
else
{
nMax=nMin=val;
isValid=true;
}
}
};
int CalcMaxGap(vector<int>&a,int len,int nMax,int nMin)
{
int Max_Gap=0;
int delta=nMax-nMin;
tagBucket *bucket=new tagBucket[len];
for (int i=0;i<len;i++)
{
int pos=(a[i]-nMin)*len/delta;
if (pos==len)
pos--;
bucket[pos].add_(a[i]);
}
int j=0;
for (int i=1;i<len;i++)
{
if (bucket[i].isValid)
{
int gap=bucket[i].nMin-bucket[j].nMax;
if (gap>Max_Gap)
{
Max_Gap=gap;
}
j=i;
}
}
return Max_Gap;
}
int main()
{
int a[8]={36,94,35,42,86,14,85,33};
int nMin=*min_element(a,a+8);
int nMax=*max_element(a,a+8);
vector<int> a_(a,a+8);
int rec=CalcMaxGap(a_,a_.size(),nMax,nMin);
cout<<"最大间距为:"<<rec;
return 0;
}
lintcode计算最大间距
最新推荐文章于 2020-11-29 01:02:03 发布