240. Search a 2D Matrix II
Leetcode
題目
解答
var searchMatrix = function (matrix, target) {
const m = matrix.length;
const n = matrix[0].length;
const binarySearch = () => {
let startRow = 0;
let endRow = m - 1;
while (startRow < endRow) {
const mid = Math.ceil((startRow + endRow) / 2);
if (matrix[mid][0] <= target) {
startRow = mid;
} else {
endRow = mid - 1;
}
}
let startCol = 0;
let endCol = n - 1;
while (startCol < endCol) {
const mid = Math.ceil((startCol + endCol) / 2);
if (matrix[startRow][mid] <= target) {
startCol = mid;
} else {
endCol = mid - 1;
}
}
return {
row: startRow,
col: startCol
};
};
let { row, col } = binarySearch();
while (row >= 0 && col < n) {
if (matrix[row][col] === target) return true;
if (matrix[row][col] < target) col++;
if (matrix[row][col] > target) row--;
}
return false;
};測資
參考資料
Last updated