在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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短