java相邻数的差不超过m_求相邻数最大间隔

ZelluX 阅读(447) 评论(0)  编辑  收藏 所属分类: Algorithm

bbb781ab6ab6623b6ea7d35fefb295af.png

Problem: You are given n real numbers - they are NOT sorted. Develop a linear time(O(n))algorithm to find the largest gap between consecutive numbers when the n numbers are sorted. For example, given:

10 23 7 1 35 27 50 41

the algorithm should produce 13 as its result, since the sorted list is:

1 7 10 23 27 35 41 50

and the largest gap is 13 (between 10 and 23).

Please note that your algorithm cannot actually sort the n numbers.

Macsy (真心) 于  (Fri Oct  5 11:59:16 2007)  提到:

有一个方法需要额外的O(n)的空间。

首先找到最大最小数max,min

max gap 肯定不小于 (max-min)/n 。

然后以(max-min)/n为步长,建立n个桶

每个桶里面记录落在这个桶中的最大最小值。

最后顺序扫描这n个桶中的值就可以了。

大概代码是

input: a[n];

min=min_of(a[1..n]);

max=max_of(a[1..n]);

step=(max-min)/n;

b[0..n].min=maxfloat; b[0..n].max=-maxfloat;

for i=1 to n

ind = (a[i]-min)/step;

b[ind].min=min(b[ind].min, a[i]);

b[ind].max=max(b[ind].max, a[i]);

maxgap=step;

last=b[0].max;

for i=1 to n

if (b[i].min != maxfloat)

maxgap=max(maxgap, b[i].min-last);

last=b[i].max;

output maxgap

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值