用 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