在JavaScript中使用数组查找特殊类型的元素
我们需要编写一个包含三个参数的JavaScript函数,即-
arr --> an array of integers m --> a positive integer n --> a positive integer
我们函数的任务是找出是否存在两个这样的元素(让它们分别称为a1和a2),以便-
a1和a2之间的绝对差最大为m
a1和a2的索引之间的绝对差最大为n
示例
以下是代码-
const arr = [1, 2, 3, 1, 7, 8];
const findSpecialElements = (arr = [], m, n) => {
const map = arr
.map((el, ind) => ({ el, ind }))
.sort((a, b) =>a.el- b.el);
let left = 0;
let right = 1;
while (right < map.length) {
const diff = Math.abs(map[right].el - map[left].el);
const range = Math.abs(map[right].ind - map[left].ind);
if (diff <= n && range <= m){
return true
}else if (diff > n){
left++;
}else if (range > m){
right++;
};
if (left === right){
right++;
};
};
return false;
};
console.log(findSpecialElements(arr, 3, 0));输出结果以下是控制台输出-
true