js数组查找最接近_数组在Javascript中获得最接近值,给定值和排序的数组正式的方式?...

If I have an array like this:

var array = [1, 3, 4, 5, 9, 10];

And I have a value like this:

var value = 8;

I want to get this result:

var result = getClosestValues(array, value); // [5, 9]

What's the correct/preferred way to do this in javascript? It seems like this is probably a formal algorithm somewhere. Maybe like this:

var getClosestValues = function(array, value) {

var low, high = 0, value;

for (var i = 0; i < array.length; i++) {

if (low <= value && low < array[i])

low = array[i];

if (high == value && high < array[i])

high = array[i];

};

return [low, high];

}

Thanks!

解决方案

If the array is sorted and large, use a binary chop to find the nearest elements:

var getClosestValues = function(a, x) {

var lo = -1, hi = a.length;

while (hi - lo > 1) {

var mid = Math.round((lo + hi)/2);

if (a[mid] <= x) {

lo = mid;

} else {

hi = mid;

}

}

if (a[lo] == x) hi = lo;

return [a[lo], a[hi]];

}

Otherwise, just scan from one end to the other, keeping track of the nearest values above and below the target. For this algorithm, your version is broken, unfortunately. Here's another version:

var getClosestValues = function(a, x) {

var lo, hi;

for (var i = a.length; i--;) {

if (a[i] <= x && (lo === undefined || lo < a[i])) lo = a[i];

if (a[i] >= x && (hi === undefined || hi > a[i])) hi = a[i];

};

return [lo, hi];

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值