用 JavaScript 搜索排序的 2 维数组
我们需要编写一个 JavaScript 函数,该函数采用一个数字数组的数组作为第一个参数,并采用一个数字作为第二个参数。子数组包含按升序排列的数字,并且前一个子数组的任何元素都不大于后一个子数组的任何元素。
此函数应使用二分查找算法在已排序的数组数组中搜索作为第二个参数提供的元素。
如果元素存在,则函数应返回 true,否则返回 false。
例如,
如果输入数组为 -
const arr = [ [2, 6, 9, 11], [13, 16, 18, 19, 21], [24, 26, 28, 31] ]; const num = 21;
则输出应为 -
const output = true;
示例
以下是代码 -
const arr = [
[2, 6, 9, 11],
[13, 16, 18, 19, 21],
[24, 26, 28, 31]
];
const num = 21;
const search2D = (array = [], target) => {
const h = array.length;
const w = h > 0 ? array[0].length : 0;
if (h === 0 || w === 0) { return false; }
const arr = getArr();
if (!arr) { return false; }
return binarySearch(arr, target) !== null;
function getArr() {
for (let i = 0; i < h; i++) {
let arr = array[i];
if (arr[0] <= target && target <= arr[arr.length - 1]) {
return arr;
}
}
return null;
}
function binarySearch(arr, t) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
if (arr[left] === t) {
return left;
}
if (arr[right] === t) {
return right;
}
let mid = Math.floor((left + right) / 2);
if (arr[mid] === t) {
return mid;
}
if (arr[mid] < t) {
left = mid + 1;
}
else if (arr[mid] > t) {
right = mid - 1;
}
}
return null;
}
};
console.log(search2D(arr, num))输出
以下是控制台输出 -
true
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP