题目
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:
每行的元素从左到右升序排列。
每列的元素从上到下升序排列。
示例 1:
输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
输出:true
示例 2:
输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
输出:false
题解一 右上角搜索
var searchMatrix = function(matrix, target) {
if(matrix.length===0)return false
let [row,col]=[0,matrix[0].length-1]// 初始化位置
while(row<=matrix.length-1&&col>=0){
if(matrix[row][col]>target){
col--
}else if(matrix[row][col]<target){
row++
}else{return true}
}
return false
};
笔记:
-
从右上角开始对比,若target大就向下,若target小就向左。
-
以左下角或右上角为根的bst
题解二 二分查找
var searchMatrix = function(matrix, target) {
for (const row of matrix) {
const index = search(row, target);
if (index >= 0) {
return true;
}
}
return false;
};
const search = (nums, target) => {
let low = 0, high = nums.length - 1;
while (low <= high) {
const mid = Math.floor((high - low) / 2) + low;
const num = nums[mid];
if (num === target) {
return mid;
} else if (num > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
笔记:
- 对每行进行二分搜索
这篇博客介绍了两种在有序矩阵中寻找目标值的高效算法:一是从右上角开始的搜索策略,当目标值大于当前元素时向下移动,小于时向左移动;二是对每一行应用二分查找的方法。这两种方法充分利用了矩阵的有序特性,提高了搜索效率。

被折叠的 条评论
为什么被折叠?



