根据值查找数组中最接近的元素,但当值超过javascript中最接近的元素时不查找

问题描述 投票:0回答:4

我想根据一个值在数组中找到最接近的元素,但想要大于或等于该值的最接近...例如,当我搜索3000及以下时,在此数组[3000,5000,8000]中它应该返回3000,但是当我搜索3001时,它应该返回5000。

这是我现在拥有的代码:

let array = [3000, 5000, 8000];

private closestNumArray(array, num) {
    var x = array.reduce(function(min, max) {
      return (Math.abs(max - num) < Math.abs(min - num) ? max : min);
    });

    return x;
  }

closesNumArray(array, 3001) // returns 3000

我希望它根据值返回5000或最近的下一个元素,但它返回3000

谢谢

javascript arrays
4个回答
1
投票

假设对数组进行排序,只需要简单的while循环即可。如果我们在数组的末尾运行(因为val太大),我们将返回数组中的最后一个值。

let array = [3000, 5000, 8000];

const closestNumArray = function(array, val) {
  i = 0;
  while (i < array.length && array[i] < val) i++;
  return array[i] || array[i-1];
}

console.log(closestNumArray(array, 2999));
console.log(closestNumArray(array, 3000));
console.log(closestNumArray(array, 3001));
console.log(closestNumArray(array, 5000));
console.log(closestNumArray(array, 5001));
console.log(closestNumArray(array, 8000));
console.log(closestNumArray(array, 8001));

0
投票

您正在寻找的是元素的lower_bound。找到要在排序数组中插入目标元素的元素位置。

let array = [3000, 5000, 8000];


array.sort();

console.log(array)

let target = 3001;
let ans = -1;
for(let i=0;i<array.length;i++){
	if(target<=array[i]){
		ans = i;
        break;
	}
}

if(ans == -1){
	console.log("Element not found");
}
else{
	console.log(array[ans]); // -1 for when all elements are smaller than target
}

0
投票

使用二进制搜索的O(log(n))中的下限元素。

let array = [3000, 5000, 8000];

array.sort();

let target = 10000;

function lower_bound(array,target){
	let low = 0, high = array.length;

	while(low < high){

		let mid = Math.floor((low+high)/2);

		if(target<=array[mid]){
			high = mid;
		}
		else{
			low = mid+1;
		}
	}
	return low;
}

let index = lower_bound(array,target);
if(index == array.length){
	console.log('Element not found')
}
else{
	console.log(array[index]);
}

0
投票

不需要对数组进行排序。

(function(array, num) { 
   return array.reduce(function(nearest, current) { 
                          return (Math.abs(current - num) < Math.abs(nearest - num))  
                                     ? current : nearest; 
                       }); 
})([3000, 5000, 8000], 4001)

返回5000,因为4001比3000更接近5000。

我不知道您为什么将您的参数命名为化简函数“ min”和“ max”,这可能会误导您?

© www.soinside.com 2019 - 2024. All rights reserved.