用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
Javascript
PHP