68 lines
1.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
const searchMatrix = function (matrix, target) {
};
/*
将二维矩阵转换成一维数组,然后利用二分查找来查找目标值。
*/
function f1(matrix, target) {
const nums = matrix.flat(); // 将二维矩阵转换为一维数组
let left = 0;
let right = nums.length - 1;
while (left <= right) {
const mid = left + Math.floor(right - left) / 2;
if (nums[mid] === target) {
return true; // 找到目标值
} if (nums[mid] < target) {
left = mid + 1; // 目标值在右半部分
} else {
right = mid - 1; // 目标值在左半部分
}
}
return false; // 矩阵中没有这个值
}
/*
两次二分查找第一次找第一列中小于等于target的那个值第二次找这一个值是否在这一行存在存在返回true,不存在返回false
*/
function f2(matrix, target) {
// 二分查找第一列这里使用upper_bound的方式
let left = 0;
let right = matrix.length;
while (left < right) {
const mid = left + Math.floor((right - left) / 2); // 使用靠右的计算防止死循环
if (matrix[mid][0] <= target) {
left = mid + 1;
} else {
right = mid;
}
}
const row = left - 1; // 右边界减1就是我们要找的值
// 如果右边界小于0表示要找的数不存在矩阵中直接返回false
if (row < 0) return false;
// 二分查找这一行
left = 0;
right = matrix[row].length;
while (left <= right) {
const mid = left + Math.floor((right - left) / 2);
if (matrix[row][mid] === target) {
return true; // 找到目标值
} if (matrix[row][mid] < target) {
left = mid + 1; // 目标值在右半部分
} else {
right = mid - 1; // 目标值在左半部分
}
}
return false; // 矩阵中没有这个值
}