เราจำเป็นต้องเขียนฟังก์ชัน 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