leetcode 240
思路
1. 矩阵特性
首先,利用矩阵的特性是解题的关键:
- 每行的元素递增
- 每列的元素递增
这意味着,如果我们在矩阵中从右上角或左下角开始搜索,可以有效缩小搜索范围
2. 从右上角开始搜索
- 将搜索的起点定位在矩阵的右上角
- 如果当前元素等于目标值,返回 true
- 如果当前元素大于目标值,则向左移动(列数 -1)
- 如果当前元素小于目标值,则向下移动(行数 +1)
- 这种方法保证每一步都在缩小查找范围,并且
时间复杂度为 O(m + n)
,其中 m 是行数,n 是列数
3. 处理边界条件
在实现过程中,需要处理好矩阵的边界条件,例如:
- 矩阵的行数和列数可以为零
- 确保不越界访问矩阵元素
参考视频:https://www.bilibili.com/video/BV1hEVWzvEsL/?spm_id_from=333.337.search-card.all.click&vd_source=ccb42000243a376a86b435878466ec00
实现
var searchMatrix = function (matrix, target) {let startRow = 0, endCol = matrix[0].length - 1;// 从右上角开始while (startRow < matrix.length && endCol >= 0) {if (matrix[startRow][endCol] === target) {return true} else if (matrix[startRow][endCol] > target) {endCol--} else {startRow++}}return false
};