本文介绍了数组在Javascript中获得最接近值,给定值和排序的数组正式的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个这样的数组:
If I have an array like this:
var array = [1, 3, 4, 5, 9, 10];
和我有一个这样的值:
var value = 8;
我要得到这样的结果:
I want to get this result:
var result = getClosestValues(array, value); // [5, 9]
什么是正确的/ preferred办法做到这一点在JavaScript?看起来这可能是一个正式的算法地方。也许是这样的:
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];
}
谢谢!
推荐答案
如果数组进行排序和大,使用二进制印章找到最近的元素:
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];
}
这篇关于数组在Javascript中获得最接近值,给定值和排序的数组正式的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!